有没有办法在jquery“when”函数中调用下一个Ajax,当被调用的函数完成时(可能是回调还是什么?)。 到目前为止,我还将此示例放在JSFiddle
中本示例中针对localhost爬虫的网址数组
var iterations = ['//localhost?p=1', '//localhost?p=2', '//localhost?p=3'];
将持有每个ajax电话
var xhr = [];
进行迭代
$.each(iterations, function(url, k){
// store every ajax function in the array
xhr.push(
$.ajax({
url: url,
cache: false,
//async: false,
dataType: "html",
success: onSuccess
})
);
})
// then must be called when all onSuccess functions are done completed (every onsuccess have their own ajax call as well)
$.when.apply($, xhr).then(function(){
alert('This must be called when all xhrs have been triggered');
})
当触发此函数内的AJAX调用时,继续下一个xhr迭代。有没有办法在onSuccess函数上放回调?
function onSuccess(data){
$.ajax({
url: 'http://localhost',
cache: false,
//async: false,
dataType: "html",
success: function(){
alert("on success 2, continue with the next xhr iteration");
},
error: function(){
alert("on error 2, continue with the next xhr iteration");
}
})
}
答案 0 :(得分:1)
以下是如何做到这一点:
使用此方法,一次只运行一个请求。如果您同时需要它们,那么您需要另一个数组来跟踪每个请求的状态。每次请求完成时,请检查您的状态数组,看看它们是否已完成循环。
答案 1 :(得分:1)
一个好的选择是创建一个类或函数来处理这种处理。你可以通过几种方式做到这一点。假设您使用实用程序类执行此操作...我可以想象它具有构造函数start()
和_next()
。
构造函数将接收并保存一组URL。
start()
将触发一个AJAX请求,其成功(可能是错误)回调到_next()
。
_next()
会查看网址数组,并选择下一个网址(这可以通过将它们从数组中移出或使用内部指针/头来完成;然后_next()
会创建另一个AJAX再次使用_next()
作为成功/错误回调。
最后,在_next()
中需要有一个终止案例,以便在没有其他网址可以调用时。