I am attempting to manipulate data loaded from a local JSON file using this method (no jQuery) but seem not to be able to access the object on a global scope:
var actual_JSON;
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
The function then is called once the document is loaded, using an anonymous function as follows:
function loaded(e) {
loadJSON( function(response) {
actual_JSON = JSON.parse(response);
console.log(actual_JSON); // Object {...}
}
);
console.log(actual_JSON); // undefined
};
document.addEventListener("DOMContentLoaded", loaded, false);
Unfortunately I don't fully understand the concept of closures yet and whether/how it affects the scope of actual_JSON
. It seems to be defined only inside the anonymous function passed to loadJSON()
as callback for XMLHttpRequest()
, although I declare it globally.