0

This code is supposed to loop through several webpages and find all the links on each page, listing them in console as it goes, but it seems to be listing only links from the very last webpage (fakeURL.com/735).

How I can get console.log(url); to work for every iteration, instead of just the last one (which is when i=735)?

for(i = 0; i <= 735; i += 15) 
{
    var xhrs = new XMLHttpRequest();
    xhrs.open("get", 'http://fakeURL.com/' + i, true);
    xhrs.onreadystatechange = function() 
    {
        if (xhrs.readyState == 4) 
        {
            $(xhrs.responseText).find('a').each(function()
            {           
                var url = $(this).attr('href');
                console.log(url);                                               
            });
        }
    }
        xhrs.send();
}
Swift
  • 54
  • 1
  • 8
  • 3
    You should see that : http://stackoverflow.com/questions/26100329/xhr-response-with-for-loop-not-working/26100409#26100409 BTW, `$` seems to be jQuery, so why don't you use `$.ajax()` ? – laruiss Oct 05 '14 at 00:25
  • Your code launches a whole bunch of ajax calls and then they all finish sometime later. What exactly is your problem? – jfriend00 Oct 05 '14 at 00:59
  • @jfriend00 I need the `console.log(url)` to happen during every iteration. Right now it only happens at the final iteration. – Swift Oct 05 '14 at 01:37

1 Answers1

1

Your issue is that you're reusing the same xhrs variable for all your ajax calls. Thus all the calls in play at once can't find the xhrs variable that belongs to their specific request when the onreadystatechange event fires. Thus, they all end up looking at the xhrs.readyState from the last request so you only ever see the last request complete.

You should be able to switch to using this to refer to the request who generated the onreadystatechange event:

for(i = 0; i <= 735; i += 15) {
    var xhrs = new XMLHttpRequest();
    xhrs.open("get", 'http://fakeURL.com/' + i, true);
    xhrs.onreadystatechange = function() 
    {
        if (this.readyState == 4) 
        {
            $(this.responseText).find('a').each(function()
            {           
                var url = $(this).attr('href');
                console.log(url);                                               
            });
        }
    }
    xhrs.send();
}

As others have said, if $ indicates that you're using jQuery, then jQuery.ajax() would likely be a lot easier.

jfriend00
  • 683,504
  • 96
  • 985
  • 979