[英]Execute callback at end of for-loop XMLHttpRequest
此代码循环浏览多个网页,在每个页面上查找链接,然后将这些链接放入名为linksArray
的数组中。 我试图在for循环在其最后一次迭代时(当x = 45时)和jQuery find().each
执行一次回调find().each
都在最后一页的所有链接中完成搜索。
由于某些原因,我没有从最后一页( http://fakeURL.com/45 )获得链接。 似乎回调函数在for循环遍历每个网页之前执行。 为什么会发生这种情况,我该如何解决?
function linkSearch(callback)
{
for(i = 0; i <= 45; i += 1)
{
ajaxCall(i);
}
var i;
var linksArray = [];
function ajaxCall (x)
{
var xhrs = new XMLHttpRequest();
xhrs.open("get", 'http://fakeURL.com/' + x, true);
xhrs.onload = function()
{
var doc = xhrs.response;
var len = $(doc).length; //will be used in telling when .each has gotten to the end of a page
$(doc).find("a[href^='http://linksFromEachPage.com/links']").each(function(index, element)
{
//below is how I'm trying to callback the linksArray when the for-loop is on its last iteration and .each has finished on the last page
thisVal = $(this).val();
if (x == 45)
{
if(parseInt(thisVal) != 0)
{
if (index == len - 1)
{
if($(doc).ajaxComplete)
{
callback(linksArray);
}
}
}
}
var url = $(this).attr('href');
linksArray[x] = url;
});
}
xhrs.responseType = 'document';
xhrs.send();
}
}
//and below is where the callback is called
linkSearch(function(theArray)
{
console.log(theArray);
});
由于您的问题是用jQuery标记的,因此这是使用jQuery进行ajax调用的代码版本,并且jQuery承诺会跟踪它们何时完成。
function linkSearch(callback) {
var i, promises = [];
for (i = 0; i <= 45; i++) {
promises.push(
$.get({url:'http://fakeURL.com/' + i, dataType:'xml'})
);
}
$.when.apply($, promises).then(function() {
var linksArray = [];
// process all results here
for (i = 0; i < arguments.length; i++){
$(arguments[i][0])
.find("a[href^='http://linksFromEachPage.com/links']")
.each(function(index, element) {
var url = $(this).attr('href');
linksArray.push(url);
});
}
callback(linksArray);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.