Read using data from an external json file without jQuery

Asked

Viewed 1,312 times

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:

JS: selecttheme.js Github

JSON: newwordlist.json Github

1 answer

1


To work the global variable with AJAX you must make a request with.

Just change this line:

httpRequest.open('GET', path, false);

Otherwise it does not work, because when printing the variable on the console, it has not yet had its value assigned. But this practice has not been recommended.

When you run the code as below, it seems at first to be unable to print the value in time:

dataJ = '';

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, false);
  httpRequest.send();
}

fetchJSONFile('json.json', function(data){
  dataJ = data;
  console.log(dataJ);
});
console.log(dataJ);

But if you go to the browser and write dataJ it will return everything. Which means that the functions that will work with the values in the course of the user’s actions will pick up the data without problem.

I would particularly use the callback for uses of return on page loading, and after loading you can use the dataJ global variable smoothly as well.

  • 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

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.