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

时间:2019-09-05 14:53:30

标签: javascript jquery ajax

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

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

我尝试过

.ajaxStop(function(){ })

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

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

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

{
 [std.format("Hello %03d", 12)]: "milk"
}

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

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

注意: 这段代码是从this answer中提取的,该代码曾被用来拦截所有ajax请求,而从this answer中则不需要在函数中传递参数:

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

答案 1 :(得分:0)

将其放在开头:

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

然后您可以稍后使用:

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

答案 2 :(得分:0)

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

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

相关问题