I'm using the code from http://www.kryptonite-dove.com/blog/load-json-file-locally-using-pure-javascript to read a json file and store it as a variable.
The code works fine; my json objects prints to the console successfully. However, I wish to access the variable outside the function. I moved the definition outside, but that does not work. What am I doing wrong?
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
var actual_JSON; <--- I moved the definition outside here
function init() {
loadJSON(function(response) {
// Parse JSON string into object
actual_JSON = JSON.parse(response);
console.log(actual_JSON); ---> this works
});
}
init();
console.log(actual_JSON); ----> this doesn't work; I get the var is undefined
loadJSONis async, the console log on the last line runs before load completes.loadcallback, or functions you're calling from there. Thus, it doesn't make sense to make it global. See stackoverflow.com/questions/14220321/… for more details and explanations.