簡體   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