jquery 记得引入
封装代码:
var ajaxObj = {
config:{
type: 'POST',
timeout: 20000, //默认超时时间
token:sessionStorage.getItem("token") || "" //登录的时候把token存一下
},
do: function (opt) {
var that = this;
var url = opt.url,
type = opt.type || that.config.type,
timeout = opt.timeout || that.config.timeout,
// 数据
data = opt.data || {},
// ajax生命周期
beforeSend = opt.beforeSend,
success = opt.success,
error = opt.error,
complete = opt.complete;
// 数据默认携带token
data.token = that.config.token;
var __ajax = $.ajax({
type: type,
url: url,
data: data,
timeout: timeout,
beforeSend: function(xhr) {
typeof beforeSend == 'function' && beforeSend(xhr)
},
success: function (res) {
if (res.code == 00) { //状态码,服务的返回结果集code为00 表示成功
typeof success == 'function' && success(res)
} else if (res.code == 01) {
alert("code:" + res.code + "," + res.message)
} else {
alert("请联系管理员!!!");
}
},
error: function () {
typeof error == 'function' && error() || alert(res.message || "网络跑丢了哦!!!");
},
complete: function (XMLHttpRequest, status) { //请求完成后最终执行参数
if (status == 'timeout') { //超时,status还有success,error等值的情况
__ajax.abort();
typeof complete == 'function' && complete(XMLHttpRequest, status) || alert('请求超时,请稍后再试!')
}
}
});
}
};
//调用
ajaxObj.do({
type:'POST', // 默认为POST 非必填项
url: 'url', // 必传
data: dataObj, //如果只传token 这行可以删除 非必填项
timeout: ‘timeout’, //默认20000毫秒 非必填项
beforeSend:function(xhr){ //实际开发过程中没有用到这个回调可以不写,下面的也一样
// 发送前
}
success:function(v){
// v为后台返回结果集
},
error:function(){
},
complete:function(XMLHttpRequest, status){
},
})
有用到模块化框架啥的可以直接把ajaxObj 这个对象导出去
alert() 可以换成 你们框架自带的比较好看友好,比如layui的弹出层 layui.msg(res.msg || "提示消息")