利用jquery的ajaxPrefilter阻止重复发送请求

利用jquery的ajaxPrefilter阻止重复发送请求

(function ($) {
    var pendingRequests = {};
    // 所有ajax请求的通用前置filter
    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {

        // 不重复发送相同请求
        var key = generatePendingRequestKey(options);
        if (!pendingRequests[key]) {
            //storePendingRequest(key, jqXHR);
            pendingRequests[key] = jqXHR;
        } else {
            // or do other
            jqXHR.abort();
        }

        var complete = options.complete;
        options.complete = function (jqXHR, textStatus) {
            // clear from pending requests
            pendingRequests[key] = null;
            if ($.isFunction(complete)) {
                complete.apply(this, arguments);
            }
        };
    });

    function generatePendingRequestKey(opts) {
        var url = opts.url;
        var type = opts.type;
        var data = opts.data;
        var str = url + type;
        if (data) {
            str += data;
        }
        return str;
    }
}(jQuery));
posted @ 2017-01-10 19:59  BornReady  阅读(1341)  评论(0编辑  收藏  举报