jQuery中AJAX二次封装
封装:
function ajax(data,func) {
$.ajax({
type: "POST",
url: data.url,
dataType: "json",
data: data.data,
beforeSend: function () {
layer.load(0, {
shade: [0.1,'#fff'] //0.1透明度的白色背景
});
},
error: function (err) {
if(err.status == 404){
layer.msg('请求失败,请求未找到');
}else if(err.status == 503){
layer.msg('请求失败,服务器内部错误');
}else {
layer.msg('请求失败,网络连接超时');
}
},
success: function (res) {
console.log(res);//控制台打印
if(res.code!=0){
layer.msg(res.msg, {icon: 5});
}
func(res);
},
complete: function () {
layer.closeAll("loading");
}
});
}
调用:
function logout(){
let data = {
url:"/login/logout",
}
ajax(data,function(res){
if(res.code==0){
window.location.href="/login"
}
});
}