简体   繁体   中英

Trying to load local json file, but can't read it in external scope

I'm trying to read in a large local .json file to be manipulated in the code I'm testing. The below snippet loads it in, and returns it to my console.

var dataset;

$.getJSON("data.json", function(json) {
 dataset = json.rows;
 console.log(dataset);
});

However, when I put console.log() outside of the function, as below, I get "undefined" returned in the console, and receive errors elsewhere when trying to use the "dataset" variable.

var dataset;

$.getJSON("data.json", function(json) {
 dataset = json.rows;
});

console.log(dataset);

New to JavaScript, but I thought you could alter an the external variable if it's declared outside of the function? Is there something with jquery or this particular function that I'm missing? The goal is to load the json's rows into a JavaScript object for manipulation, not limited to any scope.

Thanks!

You are correct about being able to alter an the external variable if it's declared outside of the function.

But the jQuery function getJSON is an asynchronous function by default which means when console.log(dataset); is called the dataset variable is still undefined .

If you were to switch console.log(dataset); to setInterval(console.log(dataset), 5000); . It would probably work but it now relies on the assumption of it always taking less or equal to than 5 seconds.

You can resolve the issue by setting your global ajax configs to disable asynchronous.

This code should work as you intend:

// Switch to synchronous functions.
$.ajaxSetup({ async: false });

var dataset;

$.getJSON("data.json", function(json) {
 dataset = json.rows;
});

console.log(dataset);

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