-- 创造无限可能

jquery技巧:终止进行中的AJAX请求

2022-11-05 18:17:50
477 人浏览 0 人点赞
有用,点赞支持一下

场景

有时发送的请求太多没有返回,为了终止之前发送的请求。也可以设置请求的超时时间

$.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);
        }
    }
});

// Everything below this is only for the jsFiddle demo
$('#cancelBtn').click(function() {
    $.xhrPool.abortAll();
});

参考:https://blog.csdn.net/fay462298322/article/details/51910565