gpt4 book ai didi

jQuery,使 ajaxQueue 出列

转载 作者:行者123 更新时间:2023-12-03 23:02:40 26 4
gpt4 key购买 nike

我正在使用示例中提到的ajaxQueue Queueing something like 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 );
});
};

我还有一个函数来进行 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 Demo 。非常感谢任何建议。

最佳答案

使用clearQueue :

ajaxQueue.clearQueue();

编辑

问题是可能仍然有一个 ajax 请求被调用。

因此您可能想要跟踪当前请求:

currentRequest = $.ajax( ajaxOpts );

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

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

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

关于jQuery,使 ajaxQueue 出列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16775447/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com