javascriptxmlhttprequestonloadonreadystatechange

Multiple xhr onload


I have this simple code for get elements from a external source

for(var i=0; i<10; i++)
    loadPage(link[i]);

function loadPage(href)
{
    var ajax = new XMLHttpRequest();
    ajax.open('get',href);
    ajax.responseType = 'document';
    ajax.onreadystatechange=function()
    {
        console.log(ajax.responseXML.querySelectorAll("a[href^='magnet']")[0].getAttribute("href"));
    }   
    ajax.send();
}

but when i read the console i get only 2 or 3 result instead of 10. i think is because i can't run multiple onload. How i can fix this?


Solution

  • By onload, you mean multiple ajax.send? that is likely not the problem.

    Could is simply be that the returned ajax isn't returning something that matches your selector (magnet) or that your server doesn't answer properly to all requests? replace your console.log with a simple console.log ("Here be dragons");

    If you ajax fetch pages from the same server, you should check the logs see how many requests do you have, and if you always reply correctly. Some servers will return at 50x error when too many requests in parallel, or put a breakpoint in your loadPage function, the pause is going to be enough to let the server process everything in time.