javascript 如何检查浏览器中是否打开了 HTTP 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9267451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if HTTP requests are open in browser?
提问by kidcapital
Is there an easy way to detect if an XMLHttpRequest is active in the browser window? Or how many are active? ie. Is there a way to detect if there are any AJAX calls active in my browser window?
有没有一种简单的方法来检测 XMLHttpRequest 在浏览器窗口中是否处于活动状态?或者有多少是活跃的?IE。有没有办法检测我的浏览器窗口中是否有任何活动的 AJAX 调用?
Extension of question:Using javascript is there a way I can see if any XMLHttpRequests are open? Such as "window.XMLisActive()" or something like that?
问题的扩展:使用 javascript 有没有办法查看是否有任何 XMLHttpRequests 打开?例如“window.XMLisActive()”之类的?
Solution: Ended up writing a wrapper for XMLHttpRequest https://gist.github.com/1820380
解决方案:最终为 XMLHttpRequest 编写了一个包装器https://gist.github.com/1820380
回答by Juan Mendes
There is not a way to detect an open connection from JS unless you write a wrapper for XmlHttpRequest
(or monkey patch it) that keeps track of opened connections.
除非您为XmlHttpRequest
(或猴子修补它)编写一个包装器来跟踪打开的连接,否则无法检测来自 JS的打开连接。
Here's kidcapital's monkey patch, not sure if it's perfect, but it's a good start
这是kidcapital的猴子补丁,不确定它是否完美,但这是一个好的开始
(function() {
var oldOpen = XMLHttpRequest.prototype.open;
window.openHTTPs = 0;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
window.openHTTPs++;
this.addEventListener("readystatechange", function() {
if(this.readyState == 4) {
window.openHTTPs--;
}
}, false);
oldOpen.call(this, method, url, async, user, pass);
}
})();
回答by vdeantoni
By using jQuery, you can keep track if there are open requests with the global event handlers: .ajaxStart()and .ajaxComplete()
通过使用jQuery,您可以使用全局事件处理程序跟踪是否有打开的请求:.ajaxStart()和.ajaxComplete()
A global variable set on ajaxStart and reset on ajaxComplete should do the job.
在 ajaxStart 上设置并在 ajaxComplete 上重置的全局变量应该可以完成这项工作。