我想根据变量立即拒绝所有 AJAX 请求。我了解如何 Hook XMLHttpRequest,但不知道如何拒绝它。
(function(open) {
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
this.addEventListener("readystatechange", function() {
if(this.readyState === 1){
// stop all ajax attempts if we're disconnected
if(!self.isConnected){
console.log('rejecting')
// reject here
this.abort(); // ???
}
}
}, false);
open.call(this, method, url, async, user, pass);
};
})(XMLHttpRequest.prototype.open);
我还想知道是否在
this.readyState === 0
类似于“请求首次开始时”调用它
最佳答案
您可以使用 abort 函数来中止 ajax 请求,首先将您的请求保存在某个变量中并对其调用 abort
$(document).ready(
var xhr;
var fn = function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};
var interval = setInterval(fn, 500);
);
还有另一种创建 AJAX 池设置的方法,我不推荐,fiddle这里
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
$.xhrPool = [];
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.xhrPool.indexOf(jqXHR);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
}
});
关于javascript - 拒绝所有 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767884/