I have a web application that receives json from a server. I was using this code:
var http_request = new XMLHttpRequest();
var url = "url where I have the json"
http_request.onreadystatechange = handle_json;
http_request.open("GET", url, true);
http_request.send(null);
var obj;
function handle_json() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var json_data = http_request.responseText;
obj = eval("(" + json_data + ")");
processData(obj);
} else {
alert("A problem ocurred");
}
http_request = null;
}
}
But now I want to receive json from two url’s and show the information. How can I do this using JavaScript? I know eval is not the appropiate thing to do but this is just a prototype.
Thank you so much! 🙂
As others have mentioned, you simply need to make 2 requests. In order to re-use the code you have already written, you could define a function to get json that takes a url argument. Something like this:
I replaced the call to eval with some logic that will call
JSON.parseif it is present, otherwise it will useeval. Using this function would allow you to make multiple requests by calling it multiple times, like so:If you wanted to process data from different urls in different ways, just define another function similar to
processDataand pass it along instead, likegetJson("some crazy url", processCrazyData);Using a framework like jQuery would reduce the amount of code that you have to write, but this solution should get it done using basic javascript.