简体   繁体   中英

XMLHttpRequest in For-Loop

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();
}

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM