1、封装ajax的方法
var token = window.localStorage.getItem("token") || ''; //后台是否需要token
/*ajax请求回调
* url:后台接口
* type:请求方法
* data:传递给后台的参数
* async:同步异步的参数(true:异步;false:同步)
* callback:成功的回调方法
* errorback:失败的回调方法
* */
window.baseurl = ' '; //后台ip和端口
(function (app, $) {
//发送请求
app.send = function (url, type, data, async, callback,errorback) {
var sendUrl = baseurl + url;
var aj = $.ajax({
url: baseurl + url,
type: type,
dataType: 'json',
data: type == 'get' ? data : JSON.stringify(data), //根据需求编辑传递参数的格式
headers: {"authorization": token},
async: async,
contentType: 'application/json;charset=utf-8',
xhrFields: {
withCredentials: true //跨域请求要想带上cookie,必须要在ajax请求里加上xhrFields: {withCredentials: true}。
},
error: function (err) {
if(errorback != undefined) {
errorback(err);
}
console.log(err)
//报错的时候提示
},
success: function (msg) {
callback(msg);
}
})
}
//用于查询
app.get = function (url, data, callback,errorback) {
app.send(url, 'get', data, true, callback,errorback)
}
//用于同步查询
app.getAsync = function (url, data, callback,errorback) {
app.send(url, 'get', data, false, callback,errorback)
}
//用于非查询请求
app.post = function (url, data, callback,errorback) {
app.send(url, 'post', data, true, callback,errorback)
}
//用于同步非查询
app.postAsync = function (url, data, callback,errorback) {
app.send(url, 'post', data, false, callback,errorback)
}
})((window.app = {}), $)
2、调用封装的ajax请求
app.get("api", ' ', function (res) { console.log(res); });
//其他方法如上格式传递参数