jQuery,如何取消ajax队列中的请求?

5

我正在使用队列技术中提到的ajaxQueue:

// 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 );
    });
};

我还有一个函数可以进行Ajax调用并将结果附加到一个div中(简化版):
function ajaxCall() {
    $.ajaxQueue({
        type: "POST",
        url: myURL,
        async: true,
        cache: false,
        success: function( result ) {
            $('#divID').append($('<div/>').html($(result).html()).fadeIn(200));
        }
    });
}

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

$("#btn").on("click", function() {
    // ( ??? ) Dequeue the ajaxQueue
    $('#divID').html(''); // Clear current results
    for(var i=0; i<15; i++) {
        ajaxCall();
    }
});
问题
如果用户在队列仍在运行时点击链接,则会添加一个新的ajax调用队列,导致结果超出预期。我需要在单击之前清除队列,然后再开始新的循环。
这里是jsFiddle演示。 非常感谢您的任何建议。

当用户第二次点击链接时,第一次点击已经检索到的结果应该发生什么? - rahul maindargi
@rahulmaindargi 我只想要清除(删除)结果。 - m.spyratos
2个回答

5
使用clearQueue
ajaxQueue.clearQueue();

编辑

问题在于可能仍会调用ajax请求。

因此,您可能希望跟踪当前请求:

currentRequest = $.ajax( ajaxOpts );

当清除队列时,中止此操作:

if (currentRequest) {
    currentRequest.abort();
}

请参见http://jsfiddle.net/4AQ9N/6/


谢谢。我已经尝试过了,但仍然有一些之前的结果留下来了。在我提供的jsFiddle示例中,如果您添加此代码,然后快速点击链接三次,结果会增加到42,而不是40。您能否尝试并让我知道? - m.spyratos
非常感谢!确实有效!我认为jQuery文档应该提到这一点... - m.spyratos
1
这只是jQuery文档中的一个小代码示例。此示例也不返回Promise,因此您无法执行类似于$.ajaxQueue({...}).done(function(response) { ... });的操作。如果您想要更完整的实现,请查看https://gist.github.com/gnarf37/1039247 - sroes

2
您需要:

   ajaxQueue.queue("fx", []); // fx is defualt queue Name. 

请参见演示

 success: function( result ) {
            if(num!=0){
                $('#divID').append($('<div/>').html('Result '+num).fadeIn(300));
            }
            num++;
        }

$("#btn").on("click", function(e) {
    e.preventDefault();
    if(ajaxQueue.queue().length>0){
        num = 0;
        ajaxQueue.queue("fx", []);
    }else{
        num = 1;
    }
    $('#divID').html(''); // Clear current results



    for(var i=0; i<40; i++) {
        ajaxCall();
    }

});

在这里,您可能会看到一个额外的输出...即多达41个。但这不是由于队列没有工作...当您清除队列时,已经放置了一个ajax调用...并正在等待响应。

在队列完成后,才会收到响应。

我已经添加了更新的代码,其中包含一些数字值的技巧。它大多数情况下都有效。


谢谢...我使用ajaxQueue.clearQueue();得到了相同的结果。如果您快速点击链接3次,结果会增加到42(每次额外的点击都会留下一个先前的结果)。您认为使用$('#divID').html('');清除先前内容有什么问题吗? - m.spyratos
嗯... num 只是一个虚拟值,用来演示我的问题。实际结果将是真正的内容。sroes 的解决方案很好。再次感谢您... - m.spyratos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接