是否可以监听所有 Ajax 调用?

mkm*_*str 2 javascript ajax http-status-code-401

我需要的是当收到错误 401(未经授权)响应时重定向到某个 url。我的代码中有几个 Ajax 调用,所以我想知道是否有一种通用方法来监听所有这些调用,并且只有当该代码返回时才重定向到该 url?

我想在所有页面中包含此代码,以便在收到它时进行重定向,而无需编辑代码中的所有 AJAX 调用。

编辑:基本上其他答案不会解释确切的模式

只需这样做即可完成:

<script>
    $(document).ajaxComplete(function(response, a){
        if(a.status == 401){
            return window.location.href = '/whatever/url/you/want';
        }
    });
</script>
Run Code Online (Sandbox Code Playgroud)

先感谢您

JUl*_*der 6

这个答案为你的问题提供了最好的答案:

为页面上的所有 AJAX 请求添加“钩子”

此代码(根据上面的答案稍作修改)说明了如何从开始到结束拦截 ajax 调用:

(function() {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function() {
        console.log('request started!');
        this.addEventListener('load', function() {
            console.log('request completed!');
            console.log("Server status code: ", this.status); 
            console.log("Ready state: ", this.readyState); 
            console.log("Server response:", this.responseText);
        });
        origOpen.apply(this, arguments);
    };
})();
Run Code Online (Sandbox Code Playgroud)

什么是readyState: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState