简体   繁体   中英

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) ?

I want to apply some event when all ajax request completed.

I have tried

.ajaxStop(function(){ })

but I want to put this block( ajaxstop ) when AJAX request exist on page.

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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