在JavaScript中,我如何测试在给定时刻是否有AJAX调用在后台运行
In JavaScript, how can I test if any AJAX call is running in the background at a given moment?
我必须使用原生javascript(尽管如果我将其转换为原生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()
来调用。
你可以在jsFiddle上看到它的作用
我知道你没有特别要求Mootools
解决方案,但我已经做了类似的事情,我想我将在这里分享给其他人参考。我通过覆盖各种请求方法来实现这一点。我目前使用的是1.5.1版本,但这或类似的东西应该在其他版本上工作。
(function() {
var requestCounter = 0,
send = Request.prototype.send,
cancel = Request.prototype.cancel,
onSuccess = Request.prototype.onSuccess,
onFailure = Request.prototype.onFailure,
timeout = Request.prototype.timeout;
var increment = function() {
++requestCounter;
};
var decrement = function() {
--requestCounter;
if (requestCounter < 0) {
requestCounter = 0;
}
};
Request.implement({
send: function() {
increment();
return send.apply(this, arguments);
},
cancel: function() {
decrement();
return cancel.apply(this, arguments);
},
onSuccess: function() {
decrement();
return onSuccess.apply(this, arguments);
},
onFailure: function() {
decrement();
return onFailure.apply(this, arguments);
},
timeout: function() {
decrement();
return timeout.apply(this, arguments);
}
});
Request.getRunningCount = function() {
return requestCounter;
};
})();
现在,每次发出请求时,计数器将增加,当它完成时,它将减少。
var request1 = new Request(...);
var request2 = new Request(...);
request1.send();
request2.send();
console.log(Request.getRunningCount()); // 2
request1.cancel();
console.log(Request.getRunningCount()); // 1
// request2 completes
console.log(Request.getRunningCount()); // 0
相关文章:
- 访问布局信息是否也会导致浏览器重排
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- 如何检测是否有溢出
- jQuery中是否内置了任何字符串格式化函数
- 是否有任何snippet或jQuery插件可以列出easylist.txt模式匹配的DOM中的所有元素
- 测试索引值是否等于某个数字的倍数
- Fancybox是否将Click事件静音
- 主干-不管怎样,检查事件以前是否绑定过
- YUI3 IO实用程序是否可以根据给定的内容类型标头值自动序列化数据
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 是否可以禁用jquery中的单个单选按钮
- 如何测试字符串是否有效日期是否使用时刻
- 时刻.js:是否可以将时间(LT)归零
- 如果多个用户在同一时刻调用Python函数,它是否工作?
- 看看当前日期是否在几个月之间的时刻j
- 在JavaScript中,我如何测试在给定时刻是否有AJAX调用在后台运行
- 时刻:查看日期是否在最近3天内