此代码循环遍历多个网页,在每个页面上查找链接,并将这些链接放入名为linksArray
的数组中。当for循环在最后一次迭代时(x = 45)并且jQuery 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);
});
答案 0 :(得分:0)
由于你的问题是用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);
});
}