在JavaScript中,如何测试给定时刻在后台是否正在运行任何AJAX调用? [英] In JavaScript, how can I test if any AJAX call is running in the background at a given moment?

查看:54
本文介绍了在JavaScript中,如何测试给定时刻在后台是否正在运行任何AJAX调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定会使用本机javascript(尽管如果将jQuery解决方案转换为本机javascript也可以使用).

I'm bound to use native javascript (although a jQuery solution can also work if I convert it to native javascript).

此外,我无法处理现有的AJAX请求,因此无法直接访问它们.

Also, I have no handles to existing AJAX requests so I can't access them directly.

我正在搜索类似的内容

var ajaxRequestsInProgress = document.getAllAjaxRunning();
ajaxRequestsInProgress[1].getStatus(); // will return the status of the request, for example

所以我可以访问该对象并检查/处理现有的ajax请求.

so I can access this object and check / manipulate existing ajax requests.

推荐答案

我们可以说这有点棘手.没有本机的方法可以做到这一点.因此,我们需要做一些修改,修改原生的 XMLHttpRequest 函数.像这样:

This is, shall we say, a little tricky. There is no native way to do it. So we need to do a bit of hacking, modifying the native XMLHttpRequest functions. Something like this:

var getAJAXRequests = (function() {
    var oldSend = XMLHttpRequest.prototype.send,
        currentRequests = [];

    XMLHttpRequest.prototype.send = function() {
        currentRequests.push(this); // add this request to the stack
        oldSend.apply(this, arguments); // run the original function

        // add an event listener to remove the object from the array
        // when the request is complete
        this.addEventListener('readystatechange', function() {
            var idx;

            if (this.readyState === XMLHttpRequest.DONE) {
                idx = currentRequests.indexOf(this);
                if (idx > -1) {
                    currentRequests.splice(idx, 1);
                }
            }
        }, false);
    };

    return function() {
        return currentRequests;
    }
}());

可以使用 getAJAXRequests()进行调用.

您可以在jsFiddle上的操作中看到它.

You can see it in action on jsFiddle.

这篇关于在JavaScript中,如何测试给定时刻在后台是否正在运行任何AJAX调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆