在JavaScript中,如何测试给定时刻在后台是否正在运行任何AJAX调用?
我一定会使用本机javascript(尽管如果将jQuery解决方案转换为本机javascript也可以使用).
I'm bound to use native javascript (although a jQuery solution can also work if I convert it to native javascript).
此外,我无法处理现有的AJAX请求,因此无法直接访问它们.
Also, I have no handles to existing AJAX requests so I can't access them directly.
我正在搜索类似的内容
var ajaxRequestsInProgress = document.getAllAjaxRunning();
ajaxRequestsInProgress[1].getStatus(); // will return the status of the request, for example
所以我可以访问该对象并检查/处理现有的ajax请求.
so I can access this object and check / manipulate existing ajax requests.
我们可以说这有点棘手.没有本机的方法可以做到这一点.因此,我们需要做一些修改,修改原生的 XMLHttpRequest
函数.像这样:
This is, shall we say, a little tricky. There is no native way to do it. So we need to do a bit of hacking, modifying the native XMLHttpRequest
functions. Something like this:
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()
进行调用.
您可以在jsFiddle上的操作中看到它.
You can see it in action on jsFiddle.