ajax-objects.js
(function () {
var $ax = function (url, success, error) {
this.url = url;
this.type = "post";
this.data = {};
this.dataType = "json";
this.async = false;
this.success = success;
this.error = error;
};
$ax.prototype = {
start : function () {
var me = this;
if (this.url.indexOf("?") == -1) {
this.url = this.url + "?jstime=" + new Date().getTime();
} else {
this.url = this.url + "&jstime=" + new Date().getTime();
}
$.ajax({
type: this.type,
url: this.url,
dataType: this.dataType,
async: this.async,
data: this.data,
beforeSend: function(data) {
},
success: function(data) {
if(data.code && data.code != 200){
Feng.error(data.message);
}else {
me.success(data);
}
},
error: function(data) {
//如果后台通过spring validator返回错误信息,则取第一条错误信息并显示
if(data.responseJSON.errors && data.responseJSON.errors.length>0){
data.responseJSON.message = data.responseJSON.errors[0].defaultMessage;
}
me.error(data);
}
});
},
set : function (key, value) {
if (typeof key == "object") {
for (var i in key) {
if (typeof i == "function")
continue;
this.data[i] = key[i];
}
} else {
this.data[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
}
return this;
},
setData : function(data){
this.data = data;
return this;
},
clear : function () {
this.data = {};
return this;
},
setType: function(type){
this.type = type;
}
};
window.$ax = $ax;
} ());
调用变的简单了
function test(id){
var ajax = new $ax("urlpath",function(data){
// 成功的回调
},function(data){
// 失败的回调
});
ajax.set("userId",id);// 设置参数
ajax.start();//真正调用
}