Read using data from an external json file without jQuery

1

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:

JS: selecttheme.js GitHub

JSON: newwordlist.json GitHub

    
asked by anonymous 15.08.2017 / 23:43

1 answer

1

To run the global variable with AJAX you must make an asynchronous request.

Just change this line:

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

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

When you run the code from the form below, it seems at first that you can not 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 in the browser inspect and type dataJ it will return everything. Which means that the functions that will work with the values in the course of the user actions will take the data without problem.

I'd particularly use the callback for return uses on the page load, and after loading you can use the global variable dataJ as well.

    
16.08.2017 / 00:33