2 回答

TA貢獻(xiàn)1851條經(jīng)驗 獲得超4個贊
// 攔截ajax請求,檢測是否超時,以重新登錄
$(document).ajaxComplete((event, xhr, settings) => {
if (xhr.status === 200) {
if (settings.dataType === 'json' && xhr.responseJSON !== void 0) {
let result = xhr.responseJSON;
if (2001 === result.code) {
// 沒有session登錄信息時跳轉(zhuǎn)至登錄頁
global.location.href = "/main-login.html";
}
}
} else if (xhr.status === 401) {} else {
global.location.href = "/main-login.html";
}
});
export default function(options) {
const defaultOptions = {
dataType: 'json',
cache: true,
jsonp: 'callback'
};
options.data = processRequest(options);
//url這里加一些代理路徑。。。
options.url = options.url;
options.headers = {
"Accept": "application/json",
"Content-Type": "application/json"
};
return $.ajax({...defaultOptions, ...options }).then(processResponse);
};
// 標(biāo)準(zhǔn)化傳給后臺的參數(shù)
function processRequest(r) {
const str = r.data || {};
if ('get' == r.method) {
if ($.isEmptyObject(str) || null == str) {
return {
t: new Date().getTime()
};
} else {
return {
//添加時間戳隨機數(shù)
params: JSON.stringify(str),
t: new Date().getTime()
};
}
} else {
return JSON.stringify(str);
}
}
// 標(biāo)準(zhǔn)化后臺相應(yīng)數(shù)據(jù)格式
function processResponse(r) {
let str = {};
if (r.rows) {
str = r;
str.code = 0;
str.list = r.rows;
delete str.rows;
} else {
if (!r.error) {
if (0 <= r.code) {
str = r;
} else {
str.code = 0;
str.data = r;
}
} else {
str.code = -1;
str.message = r.message || r.error;
}
}
return str;
}

TA貢獻(xiàn)1839條經(jīng)驗 獲得超15個贊
難道你的每個接口都直接調(diào)用了XMLHttpRequest嗎?
建議將XMLHttpRequest封裝成ajax方法提供給調(diào)用接口使用,在這個ajax方法中對返回的body json的狀態(tài)碼進行判斷及跳轉(zhuǎn)
添加回答
舉報