繁体   English   中英

如何通过JQuery检查页面上是否正在运行任何AJAX请求?

[英]How to check if any AJAX request is running on page via JQuery?

有什么办法可以找到正在页面上运行的任何AJAX请求(在$(window).load事件上)?

我想在所有ajax请求完成时应用一些事件。

我努力了

.ajaxStop(function(){ })

但是我想在页面上存在AJAX请求时放置此块( ajaxstop )。

任何帮助,将不胜感激。

确保此功能是加载到浏览器的第一件事:

(function(open) {

    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {

        this.addEventListener("readystatechange", function() {
            //Put your code here
        }, false);

        open.call(this, method, url, async, user, pass);
    };

})(XMLHttpRequest.prototype.open);

每次检索ajax响应时,都会调用以下列表器函数,并且应该在其中放置代码:

this.addEventListener("readystatechange", function() {
    //Put your code
}, false);

注意:此代码是从此答案中提取的, 该答案用于拦截所有ajax请求,并且您无需从此答案中传递函数的参数:

(function(open) {
    XMLHttpRequest.prototype.open = function() {
        this.addEventListener("readystatechange", function() {
            // put your code here!
        }, false);
        open.apply(this, arguments);
    };
})(XMLHttpRequest.prototype.open);

将此放在开头:

var ajax_running = false;
$(document).ajaxStart(function() {
  ajax_running = true;
});

然后您可以稍后使用:

$(document).ready(function() {
  if (ajax_running) {
    $(document).ajaxStop(function() {
      // do something
    })
    ajax_running = false;
  }
});

您可以执行类似的操作,这将创建一个函数,该函数将告诉您有多少个活动请求待处理。

 const activeAjaxRequests = (function(send) { var active_requests = 0; XMLHttpRequest.prototype.send = function(body) { active_requests++; this.addEventListener("readystatechange", function() { if(this.readyState === 4) active_requests--; }); send.call(this, body); }; return ()=>active_requests; })(XMLHttpRequest.prototype.send); var active_requests = activeAjaxRequests(); console.log(`There are currently ${active_requests} active ajax requests.`); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM