Javascript 拦截所有ajax调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6884616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:36:39  来源:igfitidea点击:

Intercept all ajax calls?

javascriptjqueryajaxdom-events

提问by Stann

I'm trying to intercept all AJAX calls in order to check if that AJAX response contains specific error code that I send as JSON from my PHP script (codes: ACCESS_DENIED, SYSTEM_ERROR, NOT_FOUND).

我试图拦截所有 AJAX 调用,以检查该 AJAX 响应是否包含我从 PHP 脚本作为 JSON 发送的特定错误代码(代码:ACCESS_DENIED、SYSTEM_ERROR、NOT_FOUND)。

I know one can do something like this:

我知道一个人可以做这样的事情:

$('.log').ajaxSuccess(function(e, xhr, settings) {
});

But - does this work only if "ajaxSuccess" event bubble up to .log div? Am I correct? Can I achieve what I want by binding "ajaxSuccess" event to document?

但是 - 只有当“ajaxSuccess”事件冒泡到 .log div 时,这才有效吗?我对么?我可以通过将“ajaxSuccess”事件绑定到文档来实现我想要的吗?

$(document).ajaxSuccess(function(e, xhr, settings) {
});

I can do this in either jQuery or raw JavaScript.

我可以在 jQuery 或原始 JavaScript 中做到这一点。

采纳答案by mkilmanas

From http://api.jquery.com/ajaxSuccess/:

http://api.jquery.com/ajaxSuccess/

Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.

每当 Ajax 请求成功完成时,jQuery 就会触发 ajaxSuccess 事件。任何和所有使用 .ajaxSuccess() 方法注册的处理程序都会在此时执行。

So the selector doesn't define the position where you are "catching" the event (because, honestly, ajax event by its nature doesn't start from a DOM element), but rather defines a scope to which the handling will be defaulted (i.e. thiswill poitn to that/those element(s)).

所以选择器没有定义你“捕捉”事件的位置(因为,老实说,ajax 事件本质上不是从 DOM 元素开始的),而是定义了一个处理将被默认的范围(即this将poitn到/那些元件(一个或多个))。

In summary - it should be exactly what you wish for

总而言之 - 它应该正是您想要的

回答by Andrew Newdigate

If you're using jQuery, $.ajaxSuccessis a good option, but here's a slightly more generic option that will intercept XHR calls from all frameworks (I've tested it with ExtJS and jQuery - it should work even if multiple frameworks are loaded concurrently). It's been tested to work with IE8, Chrome and Firefox.

如果您使用 jQuery,这$.ajaxSuccess是一个不错的选择,但这里有一个更通用的选项,它将拦截来自所有框架的 XHR 调用(我已经使用 ExtJS 和 jQuery 对其进行了测试 - 即使同时加载多个框架它也应该可以工作)。它已经过测试,可与 IE8、Chrome 和 Firefox 一起使用。

(function(XHR) {
    "use strict";

    var open = XHR.prototype.open;
    var send = XHR.prototype.send;

    XHR.prototype.open = function(method, url, async, user, pass) {
        this._url = url;
        open.call(this, method, url, async, user, pass);
    };

    XHR.prototype.send = function(data) {
        var self = this;
        var oldOnReadyStateChange;
        var url = this._url;

        function onReadyStateChange() {
            if(self.readyState == 4 /* complete */) {
                /* This is where you can put code that you want to execute post-complete*/
                /* URL is kept in this._url */
            }

            if(oldOnReadyStateChange) {
                oldOnReadyStateChange();
            }
        }

        /* Set xhr.noIntercept to true to disable the interceptor for a particular call */
        if(!this.noIntercept) {            
            if(this.addEventListener) {
                this.addEventListener("readystatechange", onReadyStateChange, false);
            } else {
                oldOnReadyStateChange = this.onreadystatechange; 
                this.onreadystatechange = onReadyStateChange;
            }
        }

        send.call(this, data);
    }
})(XMLHttpRequest);

I've posted a more specific example on githubwhich intercepts AJAX calls and posts the AJAX call durations back to the server for statistical analysis.

在 github 上发布了一个更具体的例子,它拦截 AJAX 调用并将 AJAX 调用持续时间发布回服务器进行统计分析。

回答by peter

The raw javacript code to intercept ajax calls:

拦截ajax调用的原始javacript代码:

(function(send) {
    XMLHttpRequest.prototype.send = function(body) {
        var info="send data\r\n"+body;
        alert(info);
        send.call(this, body);
    };
})(XMLHttpRequest.prototype.send);

The jQuery code to intercept ajax:

拦截ajax的jQuery代码:

$.ajaxSetup({
    beforeSend: function (xhr,settings) {
        alert(settings.data);
        alert(settings.url);
    }
});

Reference: http://myprogrammingnotes.com/intercept-ajax-calls-jquery.html

参考:http: //myprogrammingnotes.com/intercept-ajax-calls-jquery.html

回答by Srluisreyes

Try using Mockjax.js http://code.appendto.com/plugins/jquery-mockjax

尝试使用 Mockjax.js http://code.appendto.com/plugins/jquery-mockjax

It lets you hiHyman AJAX calls to the server and mock the location.

它允许您劫持对服务器的 AJAX 调用并模拟位置。