适用于对老项目维护时,用习惯的axios不能使用的情况
基础封装: 保留 then 的回调、baseHref、method 传 post || get || etc,
function ajax(obj) {
var callback = $.ajax({
url: window.baseHref + obj.url,
type: obj.method || "post",
data: obj.data,
dataType: 'json',
beforeSend: function(request) {
request.setRequestHeader("X-CSRF-TOKEN", window.csrf);
},
});
callback.then = function(res, rej) {
res && callback.done(res);
rej && callback.fail(rej);
return callback;
}
return callback;
}
例子,请求成功:
ajax({
url: '/webbanner',
method: 'post',
}).then(function(res) {
console.log(res)
}, function(rej) {
console.log('rej1')
}).then(function(res) {
console.log('res2')
})
// output
// 请求结果
// 'res2'
例子,请求失败:
ajax({
url: '/11111111',
method: 'post',
}).then(function(res) {
console.log(res)
}, function(rej) {
console.log('rej1')
}).then('', function(rej) {
console.log('rej2')
})
// output
// 'rej1'
// 'rej2'