The code below is supposed to loop through several webpages, each one determined by the value of i
, and the console.log(url);
line should list every URL from those webpages. Instead, the code only lists the URLs when "i" is on its final iteration (i=0) and thus it only retrieves URL's from the final webpage it requests (http://fakeURL.com/0
) - the number at the end of the URL represents "i".
How can I make the console list URL's from all iterations (when i = 45, 30, 15, and 0) instead of only the final iteration (when i = 0)?
for(i = 45; i >= 0; i -= 15)
{
var xhrs = new XMLHttpRequest();
xhrs.open("get", 'http://fakeURL.com/' + i, true);
xhrs.onload = function()
{
var doc2 = xhrs.response;
$(doc2).find('a').each(function()
{
var url = $(this).attr('href');
console.log(url);
});
}
xhrs.responseType = 'document';
xhrs.send();
}
EDIT: Below is my actual source code (unsimplified) after doing what Teemu suggested. Now 'i' is always -15 for every request the for-loop makes with the XMLHttpRequest:
var url;
var title;
function ajaxCall (x, y)
{
setTimeout(function ()
{
var xhrs = new XMLHttpRequest();
xhrs.open("get", 'http://fakeURL.com/' + i, true);
xhrs.onload = function()
{
var doc2 = xhrs.response;
$(doc2).find('a').each(function()
{
var x = $(this).attr('href');
var y = $(this).text();
console.log(x);
console.log(y);
});
}
xhrs.responseType = 'document';
xhrs.send();
}, Math.random() * 1000 + 1000);
}
for(i = 45; i >= 0; i -= 15)
{
ajaxCall(url, title);
}
Any idea why 'i' is always -15?
EDIT 2: I didn't follow Teemu's solution correctly in the code above. Here is the fixed version for future reference:
var i;
function ajaxCall (x)
{
var xhrs = new XMLHttpRequest();
xhrs.open("get", 'http://fakeURL.com/' + x, true);
xhrs.onload = function()
{
var doc2 = xhrs.response;
$(doc2).find('a').each(function()
{
var url = $(this).attr('href');
var title = $(this).text();
console.log(url);
console.log(title);
});
}
xhrs.responseType = 'document';
xhrs.send();
}
for(i = 45; i >= 0; i -= 15)
{
ajaxCall(i);
}