ajax防止重复提交

 //防止重复提交
    var pendingRequests = {};
    jQuery.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
        var key = options.url;
        i=0;
        i++;
        console.log(key+"aaaaaaaaaaa"+i);
        if (!pendingRequests[key]) {
            pendingRequests[key] = jqXHR;
        }else{
//jqXHR.abort(); //放弃后触发的提交
            setTimeout(function(){console.log("放弃先触发的提交");},1);
            pendingRequests[key].abort(); // 放弃先触发的提交
        }
        var success = options.success;
        options.success = function(jqXHR, textStatus) {
            pendingRequests[key] = null;
            if (jQuery.isFunction(success)) {
                success.apply(this, arguments);
            }
        };
        var error = options.error;
        options.error = function(jqXHR, textStatus) {
            pendingRequests[key] = null;
            if (jQuery.isFunction(error)) {
                error.apply(this, arguments);
            }
        };
    });
 
注意:ajax必须是异步时,这段代码才有效果

posted on 2017-02-17 09:41  杨龙飞  阅读(248)  评论(0编辑  收藏  举报

导航

Fork me on GitHub