我正在尝试将按顺序执行的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端放置一个错误,然后调用4次queueAjax,并且每次运行4次。如您所见,我尝试使用$ .clearQueue扩展jQuery,并且尝试将队列作为参数传递给ajax函数,但没有成功。任何输入将不胜感激。谢谢
答案 0 :(得分:0)
我似乎已经解决了它,我在$ .clearQueue定义中处于正确的轨道,我只是在调用ajaxQueue.clearQueue()之前删除了ajaxQueue = $({}),现在似乎可以正常工作了。我认为使用ajaxQueue = $({})本身就是尝试清除队列,我只是重新分配了ajaxQueue变量并且没有将其清空,因此当我随后调用.clearQueue()时没有任何作用>