I have a webpage that will load a couple JSON
files via XMLHttpRequest
.
I want to load the file, parse the JSON
and store the output in a globally accessible variable.
Once BOTH foo
and bar
are complete, only then do I want to call the success()
function. So far, my script has 2 problems that I need help with.
1: I'm having trouble setting the variable to the output of loadJSON()
. My guess is that my return statements are a little funky? I've tried everything... help?
2: How do I call success()
only AFTER BOTH foo
and bar
are set?
var foo;
var bar;
function initSession(){
foo = loadJSON("foo.js");
bar = loadJSON("bar.js");
}
My guess is that the problem lies in how I'm using return in the loadJSON()
function:
function loadJSON(url){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
return JSON.parse(xhr.responseText); // doesn't work?
}
}
xhr.open("GET", url, true);
xhr.send();
return xhr.onreadystatechange;
}
$(document).ready(function(){
initSession();
});
function success(){
$("body").append(foo[0]);
$("body").append(bar[0]);
}
Thank you!