简体   繁体   中英

JS: Loaded json undefined, even though it is not

I am trying to load an array via json with this function I mostly stole from W3 schools:

function load_json_data(path, callback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4 && httpRequest.status === 200) {
      var data = JSON.parse(httpRequest.responseText);
      if (callback) callback(data);
    }
  };
  httpRequest.open('GET', path);
  httpRequest.send();
}

I have a second function that is supposed to graph the data, but let's pretend it just prints the array. (It also doesn't graph them so it's not just a display error):

function create_graph(data) {
    console.log(data);
}

Now, outside of any function, I am doing this:

var data;
load_json_data(
  "./test.json",
  function(return_data) {
    data = return_data;
  }
);
console.log("Loaded Data: " + data)
create_graph(data);

So I'm loading "./test.json" and passing that to the function. Unfortunately the output says, data is undefined, but when I access the variable manually I get the right output:

Loaded Data: undefined
Received Data: undefined
> data
(6) [0.6, 0.55, 0.45, 0.4, 0.7, 0.66]

I'm coming from c and python so I'm assuming the interpreter is hiding something from me. Why is the variable undefined after the load function ran, but defined, when I access it?

When you provide a callback that sets data , you're basically telling JS "make the HTTP request, set the data variable when it's done, but in the meantime keep running the code that comes afterwards." If you want data to be set, you have to move the code that uses data into the callback:

var data;
load_json_data(
  "./test.json",
  function(return_data) {
    data = return_data;
    console.log("Loaded Data: " + data)
    create_graph(data);
  }
);

You should also consider migrating to the fetch API as well as using promises :

function load_json_data(path, callback) {
  return fetch(path).then(res => res.json());
}

load_json_data("./test.json", function(data) {
  console.log("Loaded data: " + data);
  create_graph(data);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM