[英]Issue with loading data from JSON file
I am trying to load the content of a json file into an array. 我正在尝试将json文件的内容加载到数组中。 Instead of using the callback function to ensure file is loaded before I use it, I coded it like this:
我没有使用回调函数来确保在使用文件之前已加载文件,而是将其编码为:
var f_file_loaded = false;
var data = null;
$.getJSON('transformation.json', function(dt){
f_file_loaded = true;
data = dt;
});
while(!f_file_loaded){
// Loop until file is loaded
}
console.log('data loaded', data);
This however, blocks the browser and the f_file_loaded doesn't seem to go true any time. 但是,这会阻塞浏览器,并且f_file_loaded似乎随时都无法实现。 What is the problem with my code?
我的代码有什么问题?
while(!f_file_loaded){
doesn't work as you expect...it just creates an infinite loop. while(!f_file_loaded){
不能按您期望的那样工作...它只会创建一个无限循环。
You need to use the promise()
interface. 您需要使用
promise()
接口。
$.when($.getJSON()).done(function() {
// file is loaded, execute whatever code
});
That's because $.getJSON is an async call. 那是因为$ .getJSON是一个异步调用。
You should do something along these lines: 您应该按照以下步骤进行操作:
function data_loaded(data) {
console.log('data loaded', data);
}
$.getJSON('transformation.json', function(dt){
data_loaded(dt);
});
if you want to do sync not async call, then use this 如果您要进行同步而不是异步调用,请使用此
your code above 您上面的代码
$.ajax("transformation.json", {
dataType:'json',
async:false,
success:function(dt) {
data = dt;
}
});
your code below will continue execution after data is downloaded 下载数据后,您下面的代码将继续执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.