Apologies for the very beginner question.
I'm trying to use this answer to read in data in a JSON file into my javascript. I've pasted the code from the answer directly into the top of my javascript (changing pathToFile.json
obviously). What I'm not sure about is what I'm supposed to do where the "do something with your data" comment is. I just want to have the parsed data
object available to the rest of my code, but being extremely new to javascript I don't really understand how the callback function works. I can see the data from the JSON file logged in the console when I run it but every (no doubt dumb) thing I've tried to do to 'get it out' of the function hasn't worked -- I get a ReferenceError: data is not defined
message when I try to refer to it later.
Here's the code from the other answer:
function fetchJSONFile(path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', path);
httpRequest.send();
}
// this requests the file and executes a callback with the parsed result once
// it is available
fetchJSONFile('pathToFile.json', function(data){
// do something with your data
console.log(data);
});