简体   繁体   English

尝试加载本地json文件,但无法在外部范围内读取它

[英]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. 我正在尝试读取一个较大的本地.json文件,以在我正在测试的代码中对其进行操作。 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. 但是,当我将console.log() 放在函数外部时,如下所示,我在控制台中返回“ undefined”,并且在尝试使用“ dataset”变量时在其他地方收到错误。

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? JavaScript的新手,但是我认为如果在函数外部声明了外部变量,您可以更改它吗? Is there something with jquery or this particular function that I'm missing? jQuery是否有某些东西或我缺少的特定功能? The goal is to load the json's rows into a JavaScript object for manipulation, not limited to any scope. 目标是将json的行加载到JavaScript对象中进行操作,而不限于任何范围。

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); 但是jQuery函数getJSON默认情况下是一个异步函数 ,这意味着当console.log(dataset); is called the dataset variable is still undefined . 被称为dataset变量仍未undefined

If you were to switch console.log(dataset); 如果要切换console.log(dataset); to setInterval(console.log(dataset), 5000); 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. 它可能会起作用,但是现在依赖于始终花费少于或等于5秒的假设。

You can resolve the issue by setting your global ajax configs to disable asynchronous. 您可以通过将全局ajax配置设置为禁用异步来解决此问题。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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