jQuery,出一个ajaxQueue

m.s*_*tos 5 ajax jquery

我正在使用示例中提到的ajaxQueue 像Ajax Calls那样排队:

// jQuery on an empty object, we are going to use this as our queue
var ajaxQueue = $({});
$.ajaxQueue = function( ajaxOpts ) {
    // Hold the original complete function.
    var oldComplete = ajaxOpts.complete;
    // Queue our ajax request.
    ajaxQueue.queue(function( next ) {
        // Create a complete callback to fire the next event in the queue.
        ajaxOpts.complete = function() {
            // Fire the original complete if it was there.
            if ( oldComplete ) {
                oldComplete.apply( this, arguments );
            }
            // Run the next query in the queue.
            next();
        };
        // Run the query.
        $.ajax( ajaxOpts );
    });
};
Run Code Online (Sandbox Code Playgroud)

我还有一个函数来进行Ajax调用并将结果附加到div(简化):

function ajaxCall() {
    $.ajaxQueue({
        type: "POST",
        url: myURL,
        async: true,
        cache: false,
        success: function( result ) {
            $('#divID').append($('<div/>').html($(result).html()).fadeIn(200));
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

然后在点击事件中,我循环通过ajax调用(简化):

$("#btn").on("click", function() {
    // ( ??? ) Dequeue the ajaxQueue
    $('#divID').html(''); // Clear current results
    for(var i=0; i<15; i++) {
        ajaxCall();
    }
});
Run Code Online (Sandbox Code Playgroud)

问题
如果用户在队列仍在运行时单击链接,则会添加一个新的ajax调用队列,从而产生比预期更多的结果.在新循环开始之前,我需要在点击时清除队列.

这是一个jsFiddle演示.任何建议非常感谢.

sro*_*oes 5

使用clearQueue:

ajaxQueue.clearQueue();
Run Code Online (Sandbox Code Playgroud)

编辑

问题是可能仍然会调用ajax请求.

所以你可能想跟踪当前的请求:

currentRequest = $.ajax( ajaxOpts );
Run Code Online (Sandbox Code Playgroud)

并在清除队列时中止此操作:

if (currentRequest) {
    currentRequest.abort();
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/4AQ9N/6/