使用 Jquery 队列执行 Ajax 调用序列,如果请求失败,需要清除队列



我正在尝试建立ajax调用队列,这些调用将按顺序执行。它似乎工作正常,问题是如果任何调用中出现错误,我希望队列在错误后停止,以便不执行队列中的剩余 ajax 调用。

我对jquery队列的想法有点陌生,我在网上找到了这段代码来扩展jquery:

var ajaxQueue = $({});
(function($) {
$.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);    
next(); // run the next query in the queue
};
// run the query
$.ajax(ajaxOpts);
});
};
// this is my addition, in an attempt to find ways to clear the queue
$.clearQueue = function(ajaxQueue) {
ajaxQueue.clearQueue();
ajaxQueue.stop();
};
})(jQuery);

然后我有这个功能将项目添加到队列中

function queueAjax( passObj, success, ajaxQueue ) {
$.ajaxQueue({
url: route() + 'global_fxns/ajaxHub',
async: true,
data: {'passme' : encodeURIComponent( JSON.stringify( passObj ) ) },
success: function(data) {
var aJSON = decodeURIComponent(data);       
var retObj = $.parseJSON(aJSON);    
// if there was no problem, call the success function that was passed
success( passObj, retObj );                    
},
error: function ( jqXHR, textStatus, errorThrown) {
clog("error");
// again this is my addition, trying to find ways to clear queue        
ajaxQueue = $({});
$.clearQueue(ajaxQueue);
} 
});

最后调用 queueAjax:

var arr = standardAjaxArray( "testQueue", 0 );
var obj1 = { 
arr: arr,
count: 1
};
function success( passObj, retObj, ajaxQueue ) {
clog("Queue success!");
}
queueAjax( obj1, success );

问题是无论我尝试什么,如果 ajax 调用中出现错误,我都无法让队列清空。我故意在 ajax PHP 端放了一个错误,然后调用 queueAjax 4 次,每次运行 4 次。如您所见,我尝试使用$.clearQueue扩展jQuery,并且还尝试将队列作为参数传递到ajax函数中,但没有成功。任何意见将不胜感激。谢谢

我似乎已经解决了它,我在 $.clearQueue 定义中走在正确的轨道上,我刚刚在调用 ajaxQueue.clearQueue(( 之前删除了 ajaxQueue = $({}(,它现在似乎可以工作了。我认为通过使用 ajaxQueue = $({}(,这本身就是试图清除队列,我只是重新分配 ajaxQueue 变量而不是清空它,所以当我随后调用 .clearQueue(( 时没有任何效果

最新更新