基于JQuery二次封装Ajax
为什么要再次封装Ajax呢?
封装是为了达到统一处理接口返回的状态,不需要每次调用都去写,比如: 统一处理登录、权限等问题。这些问题的处理是每个接口都需要的,封闭起来便于管理修改。
Promise版本
let StPAjax = {
promise : null,
request : function(options,dataJson){
let opts = $.extend({},{
limit:true,
timer:null,
type:"POST",
path: basePath, // 接口地址
showMsg: false, // 显示提示信息
showFailMsg: false, // 只提示失败信息
dataType : "json",
showLoad : false, // 显示加载中。。。
processData: true, // 文件上传时,使用 即:cType为2时
cType: 0,
contentType: [
"application/x-www-form-urlencoded; charset=UTF-8",
"application/json; charset=utf-8",
false,
"text/plain;charset=UTF-8"
],
before:function(request){
},error:function(){
},success:function(data){
}},options);
let _url = opts.url;
if(isEmpty(_url)){
_url = "/"+opts.model+"/"+opts.method;
}
if(isNotEmpty(opts.params)){
_url+="&"+opts.params;
}
if (opts.cType == 2) {
opts.processData = false;
let formData = new FormData();
for (const key in dataJson) {
if (dataJson.hasOwnProperty(key)) {
formData.append(key, dataJson[key]);
}
}
dataJson = formData;
}
return StPAjax .ajaxMain(opts,_url,dataJson);
},
ajaxMain:function(opts,_url,dataJson){
if(opts.showLoad)layer.load();
this.promise = new Promise(function (resolve, reject) {
$.ajax({
type: opts.type,
data : dataJson,
dataType: opts.dataType,
url : opts.path + _url,
contentType: opts.contentType[opts.cType],
processData: opts.processData,
beforeSend:function(request){
opts.before(request);
// request.setRequestHeader("X-Requested-With","xmlhttprequest");
},
error:function(data){
layer.msg('抱歉!操作不能够及时响应,请稍后在试...!',{icon:1,time:1000});
// stars.prompt({text:"抱歉!操作不能够及时响应,请稍后在试...",color:"#f15949"});
reject(data);
opts.error(data);
clearTimeout(opts.timer);
},
success:function(data){
let result = data;
if(typeof data === "string"){
result = JSON.parse(data);
}
if (result.code === -500) {
layer.msg("接口异常:" + result.msg,{ icon: 5,time: 2000 });
} else {
resolve(result)
clearTimeout(opts.timer);
if(opts.success)opts.success(result);
}
if (data.code != 0 && opts.showFailMsg) {
parent.layer.msg(data.msg,{ icon: 5 });
}
if (opts.showMsg) {
parent.layer.msg(data.msg,{ icon:data.code === 0?6:5 });
}
},
complete(){
if(opts.showLoad)layer.closeAll('loading');
if (opts.complete) opst.complete();
}
});
})
return this.promise;
}
};
普通版本
采用截流的方式封装,可以达到防止用户恶意点击的目的;
let StAjax = {
request : function(options,dataJson){
let opts = $.extend({},{
limit:true,
timer:null,
delay: 200, // 截流延时时间
type:"POST",
path: basePath, // 接口地址
showMsg: false, // 显示提示信息
showFailMsg: false, // 只提示失败信息
dataType : "json",
showLoad : false, // 显示加载中。。。
processData: true, // 文件上传时,使用 即:cType为2时
cType: 0,
contentType: [
"application/x-www-form-urlencoded; charset=UTF-8",
"application/json; charset=utf-8",
false,
"text/plain;charset=UTF-8"
],
before: function(request){},
error: function(){},
success: function(data){},
complete: function() {}
}, options);
let _url = opts.url;
if(isEmpty(_url)){
_url = "/"+opts.model+"/"+opts.method;
}
if(isNotEmpty(opts.params)){
_url+="&"+opts.params;
}
if (opts.cType == 2) {
opts.processData = false;
let formData = new FormData();
for (const key in dataJson) {
if (dataJson.hasOwnProperty(key)) {
formData.append(key, dataJson[key]);
}
}
dataJson = formData;
}
clearTimeout(opts.timer);
opts.timer = setTimeout(() => {
StAjax .ajaxMain(opts,_url,dataJson);
}, opts.delay);
},
ajaxMain:function(opts,_url,dataJson){
if(opts.showLoad)layer.load();
$.ajax({
type: opts.type,
data : dataJson,
dataType: opts.dataType,
url : opts.path + _url,
contentType: opts.contentType[opts.cType],
processData: opts.processData,
beforeSend:function(request){
opts.before(request);
// request.setRequestHeader("X-Requested-With","xmlhttprequest");
},
error:function(data){
layer.msg('抱歉!操作不能够及时响应,请稍后在试...!',{icon:1,time:1000});
opts.error(data);
clearTimeout(opts.timer);
},
success:function(data){
let result = data;
if(typeof data === "string"){
result = JSON.parse(data);
}
if (result.code === -500) {
layer.msg("接口异常:" + result.msg,{ icon: 5,time: 2000 });
} else {
clearTimeout(opts.timer);
if(opts.success)opts.success(result);
}
if (data.code != 0 && opts.showFailMsg) {
parent.layer.msg(data.msg,{ icon: 5 });
}
if (opts.showMsg) {
parent.layer.msg(data.msg,{ icon:data.code === 0?6:5 });
}
},
complete(XMLHttpRequest, textStatus){
if(opts.showLoad)layer.closeAll('loading');
if (opts.complete) opts.complete();
}
});
}
};
使用方法
第一种方法:
stAjax.request({
url : $http.addcards,
showMsg: true,
success: function (res) {
console.log(res);
},
complete: function () {
mask = true;
}
},{
card_ids : couponIds,
buyer_ids : buyerId,
type : buyerNum
});
StPAjax.request({
url : "/user/ShopCoupon",
showMsg: true
}, {
card_ids : couponIds,
buyer_ids : buyerId,
type : buyerNum
}).then(res => {
if(res.code === 0){
...
}
}).catch( e => console.log(e));
第二种方法:
stAjax.request({
path: "", // 个别的接口,其他接口地址时传
model: "order",
method: "list",
showFailMsg: true,
success: function (res) {
console.log(res);
}
},{
page: 1,
pageSize: 10
});
StPAjax.request({
model: "user",
method: "list",
showFailMsg: true
}, {
page: 1,
pageSize: 10
}).then(res => {
if(res.code === 0){
...
}
}).catch( e => console.log(e));