1
I have an external json file and want to use its data in various functions I have, but I’m not getting, 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 first console.log(date); returns exactly what I want and how I want, but the second does not work at all. I have tried to define a var data; before all this but it still doesn’t work.
Note: I am not using jQuery anywhere in the project and I don’t think it would be good to call the whole library just to call the json.
Links:
JSON: newwordlist.json Github
Now I have already given a light on what and how I can do, I will give a better search on the use of callback because the browser’s Inspect already "cursed" me. Thank you
– Matheus Ramos
The Inspect swears because of the asynchronous. So I wouldn’t even use it. I would do in the callback that would be in the lines inside the call of the fetchJSONFile there.
– Karl Zillner