- 原理就是把pending状态时的res存入全局变量中,pending过程时对这些res进行选择性abort
- 感觉比单独设置一个flag方便,且适应型广
当只需要最后一次ajax
window.pendingRequests = {};
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var key = options.url+Math.random();
if (!pendingRequests[key] && key.indexOf('.html') == -1) {
pendingRequests[key] =jqXHR;
}
for(let i in pendingRequests)
if(i!=key){
pendingRequests[i].abort()
}
var complete = options.complete;
options.complete = function (jqXHR, textStatus) {
delete pendingRequests[key];
if ($.isFunction(complete)) {
complete.apply(this, arguments);
}
};
});
当只需要第一次ajax
window.pendingRequests = {};
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var key=options.url;
if (!pendingRequests[key] && key.indexOf('.html') == -1) {
pendingRequests[key] =jqXHR;
} else if (key.indexOf('.html') == -1) {
jqXHR.abort();
}
var complete = options.complete;
options.complete = function (jqXHR, textStatus) {
delete pendingRequests[key];
if ($.isFunction(complete)) {
complete.apply(this, arguments);
}
};
});
同时执行多个不同api接口的且需要各自的最后一次时的ajax
window.pendingRequests = {};
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var key=options.url
if (!pendingRequests[key] && key.indexOf('.html') == -1) {
console.log(false)
pendingRequests[key]=[]
pendingRequests[key].push(jqXHR)
}else{
console.log(true)
pendingRequests[key].push(jqXHR)
}
for(let i in pendingRequests){
let len=pendingRequests[i].length
for(let j=0;j<len-1;j++){
pendingRequests[i][j].abort()
}
}
setTimeout(function () {
var complete = options.complete;
options.complete = function (jqXHR, textStatus) {
delete pendingRequests[key];
if ($.isFunction(complete)) {
complete.apply(this, arguments);
}
};
},0)
});