简体   繁体   English

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

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

Is there any way to find any AJAX request is running on page (on $(window).load event) ? 有什么办法可以找到正在页面上运行的任何AJAX请求(在$(window).load事件上)?

I want to apply some event when all ajax request completed. 我想在所有ajax请求完成时应用一些事件。

I have tried 我努力了

.ajaxStop(function(){ })

but I want to put this block( ajaxstop ) when AJAX request exist on page. 但是我想在页面上存在AJAX请求时放置此块( ajaxstop )。

Any help would be appreciated. 任何帮助,将不胜感激。

Make sure this functions is the first thing loaded to the browser: 确保此功能是加载到浏览器的第一件事:

(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);

Each time an ajax response is retrieve, the following listner functions is called, and is in there that you should put your code: 每次检索ajax响应时,都会调用以下列表器函数,并且应该在其中放置代码:

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

Note: This code was extracted from this answer which was used to intercept all ajax requests and from this answer you don't need to pass the parameters on functions: 注意:此代码是从此答案中提取的, 该答案用于拦截所有ajax请求,并且您无需从此答案中传递函数的参数:

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

Put this at the beginning: 将此放在开头:

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

Then you can later use: 然后您可以稍后使用:

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

You can do something like this, which creates a function that will tell you how many active requests are pending. 您可以执行类似的操作,这将创建一个函数,该函数将告诉您有多少个活动请求待处理。

 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