This code loops through several webpages, finds links on each page, and puts those links into an array called linksArray
. I've tried to execute a callback when the for-loop is on its last iteration (when x =45) and the jQuery find().each
has finished searching through all of the last page for links.
For some reason, I'm not getting links from the very last page ( http://fakeURL.com/45 ). It seems that the callback function executes before the for-loop has gone through every webpage. Why is this happening and how do I fix it?
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);
});
Since your question is tagged with jQuery, here's a version of your code that uses jQuery for the ajax call and jQuery promises to keep track of when they are all done.
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);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.