weixin_33743880 2016-06-11 19:43 采纳率: 0%
浏览 40

拒绝所有AJAX请求

I want to immediately reject all AJAX requests depending on a variable. I understand how to hook the XMLHttpRequest but not sure how to reject it.

(function(open) {
            XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
                this.addEventListener("readystatechange", function() {
                    if(this.readyState === 1){
                        // stop all ajax attempts if we're disconnected
                        if(!self.isConnected){
                            console.log('rejecting')
                            // reject here
                            this.abort(); // ???
                        }
                    }
                }, false);
                open.call(this, method, url, async, user, pass);
            };
        })(XMLHttpRequest.prototype.open);

Also I want to know if calling this within this.readyState === 0 is akin to calling it "when the request first starts"

  • 写回答

2条回答 默认 最新

  • weixin_33691598 2016-06-11 19:46
    关注

    you can use abort function to abort the ajax request, first save your request in some variable and call abort on it

    $(document).ready(
        var xhr;
    
        var fn = function(){
            if(xhr && xhr.readyState != 4){
                xhr.abort();
            }
            xhr = $.ajax({
                url: 'ajax/progress.ftl',
                success: function(data) {
                    //do something
                }
            });
        };
    
        var interval = setInterval(fn, 500);
    );
    

    There is another approach of creating AJAX Pool setup, which I don't recommend, fiddle here

    $.xhrPool = [];
    $.xhrPool.abortAll = function() {
        $(this).each(function(idx, jqXHR) {
            jqXHR.abort();
        });
        $.xhrPool = [];
    };
    
    $.ajaxSetup({
        beforeSend: function(jqXHR) {
            $.xhrPool.push(jqXHR);
        },
        complete: function(jqXHR) {
            var index = $.xhrPool.indexOf(jqXHR);
            if (index > -1) {
                $.xhrPool.splice(index, 1);
            }
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题