I have an external json file and I want to use its data in several functions that I have, but I can not, only when I put all the json inside a variable.
I researched and ended up finding this example:
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();
}
fetchJSONFile('js/newwordlist.json', function(data){
console.log(data);
});
console.log(data); //Nao retorna
This 1st console.log (data); returns exactly what I want and how I want it, but the second one is nothing. I've already tried setting a var data; before all this but it still does not work.
Note: I'm not using jQuery anywhere in the project and I think it would not be good to call the whole library just to call json.
Links:
JSON: newwordlist.json GitHub