loadJSON(path, callback) {
console.log("path: " + path);
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', path, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
Above is a function to access a json file locally. Then from `foobar()' parse the data retrieved. However from "outside" of call back function, the variable "json" cannot be accessed. I had searched similar SO questions and async concepts but still was not able to figure a way to resolve it.
function foobar() {
var json;
loadJSON("data.json", function(response) {
json = JSON.parse(response);
console.log(json[0].name); // Successfully shows the result
});
console.log(json[0].name); // TypeError: json is undefined
}
Is there a way to access the variable "outside" of the callback?