我必须使用 native javascript(尽管如果我将其转换为 native javascript,jQuery 解决方案也可以工作)。
此外,我没有现有 AJAX 请求的句柄,因此无法直接访问它们。
我正在寻找类似的东西:
var ajaxRequestsInProgress = document.getAllAjaxRunning();
ajaxRequestsInProgress[1].getStatus(); // will return the status of the request, for example
这样我就可以访问这个对象并检查/操作现有的 ajax 请求。
最佳答案
我们应该说,这有点棘手。没有本地方法可以做到这一点。所以我们需要做一些修改,修改原生的 XMLHttpRequest
函数。像这样:
var getAJAXRequests = (function() {
var oldSend = XMLHttpRequest.prototype.send,
currentRequests = [];
XMLHttpRequest.prototype.send = function() {
currentRequests.push(this); // add this request to the stack
oldSend.apply(this, arguments); // run the original function
// add an event listener to remove the object from the array
// when the request is complete
this.addEventListener('readystatechange', function() {
var idx;
if (this.readyState === XMLHttpRequest.DONE) {
idx = currentRequests.indexOf(this);
if (idx > -1) {
currentRequests.splice(idx, 1);
}
}
}, false);
};
return function() {
return currentRequests;
}
}());
可以用getAJAXRequests()
调用。
您可以在实际中看到它 on jsFiddle .
关于javascript - 在 JavaScript 中,我如何测试在给定时刻是否有任何 AJAX 调用在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23674175/