简体   繁体   中英

making multiple HTTP GET requests with javascript

I am attempting to make multiple http get requests in js. but I'm a total noob. I would not be opposed to jQuery either. The idea is I make a call to my server so I can populate a js chart.

var client;
function handler() { 
    if(client.readyState == 4 && client.status == 200) { 
        // make a chart
    }
} 

window.onload = function() { 
    client = new XMLHttpRequest(); 
    client.onreadystatechanged = handler; 
    client.open("GET", "http://someurl/stuff"); 
    client.send();
}

so the above is the basic idea of a web request. It seems that the handler acts a callback or event. this works when creating one get request. but if I make two or more, then I get mixed results. sometimes all requests will work, other times none, or just one. the error that occurs is the connection has not been closed.

The primary issue with this code is that it uses the same global variables (eg client ) which will just fail for multiple requests as they become clobbered .

(The issue that the order of the handler invocations is undefined due to the asynchronous nature of the requests is only secondary to the lack of re-entrancy of creating/using the XHR object in the given code - there is no way that the handler is guaranteed the correct XHR object when it access the client variable!)

Closures and objects avoid this issue but .. just use jQuery (or whatever library you prefer that provides a nice XHR interface, preferably with Promises).

Since you "would not be opposed to jquery", then use it . Take care to only do work from within the callbacks (or promise handlers) using the returned data they provide - this is because the requests are, well, asynchronous.

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