动态设置,每次都会执行beforeSend
//ajax监听
$.ajaxSetup({
//请求csrf-token
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', localStorage.getItem('__token__'))
},
//请求完毕更新csrf-token
complete: function (xhr, status) {
localStorage.setItem('__token__', xhr.getResponseHeader('__token__'));
}
});
或者直接设置header
$.ajaxSetup({
timeout: 1000, //超时时间设置,单位毫秒
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//请求csrf-token
beforeSend: function (xhr) {
},
//请求完毕更新csrf-token
complete: function (xhr, status) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if(xhr.responseJSON.code === 10000){
Toast.fire({
icon: 'error',
title: xhr.responseJSON.msg
})
}
}
}
//超时,status还有success,error等值的情况
if (status === 'timeout') {
Toast.fire({
icon: 'error',
title: "请求超时~"
})
}
}
});