-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.autoajax.js
More file actions
90 lines (81 loc) · 3.66 KB
/
jquery.autoajax.js
File metadata and controls
90 lines (81 loc) · 3.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
$.fn.autoAjax = function(method, options){
if(!method){
var self = this;
var protoObject = {
_selector: null,
_handlers : {},
_actFunc: null,
addHandlers: function(callbacks){
for (var name in callbacks){
this._handlers[name] = callbacks[name];
}
},
removeHandler: function(name){
delete this._handlers[name];
},
resetHandlers: function(){
this._handlers = {};
},
setSuccess: function(name){
self.attr('data-success', name);
},
setError: function(name){
self.attr('data-error', name);
},
remove: function(){
if(this._selector){
$('body').off('submit', this._selector, this._actFunc);
delete $.fn.autoAjax._instances[this._selector];
}else{
$(this._selector).off('submit', this._actFunc);
$(this).data('autoAjax', null);
}
}
};
protoObject._actFunc = function(e){
e.preventDefault();
var frm = $(this);
var formData = new FormData($(this).get(0));
$.ajax({
url: frm.attr('action'),
type: frm.attr('method'),
data: formData,
processData: false,
contentType: false,
success: protoObject._handlers[frm.attr('data-success') || 'defaultSuccess'] || function(data){
console.log(data);
},
error: protoObject._handlers[frm.attr('data-error') || 'defaultError'] || function(error){
console.log(error);
}
});
};
if(this.selector){
protoObject._selector = this.selector;
$('body').on('submit', this.selector, protoObject._actFunc);
$.fn.autoAjax._instances[this.selector] = protoObject;
}else if(this.length>1){
this.each(function(){
$(this).on('submit', protoObject._actFunc);
$(this).data('autoAjax', protoObject);
});
}else if(this.length===1){
this.on('submit', protoObject._actFunc);
this.data('autoAjax', protoObject);
}
return this;
}else{
if(this.selector){
if ($.fn.autoAjax._instances[this.selector]){
$.fn.autoAjax._instances[this.selector][method](options);
}
return this;
}else{
this.each(function(){
if(!$(this).data('autoAjax')) $(this).autoAjax();
$(this).data('autoAjax')[method](options);
});
}
}
};
$.fn.autoAjax._instances = {};