【发布时间】:2021-04-10 09:27:47
【问题描述】:
我正在尝试将 json 内容从本地文件传递到变量,以便动态地提供下拉列表。如果我对 json 数据进行硬编码,下面的代码可以正常工作,但是我很难初始化从本地文件接收 json 的变量...我获取它,在控制台中打印它,但是我的 var之后仍然未定义。
https://jsfiddle.net/ssoj_tellig/zo85r30x/10/
// test to pass json content to var mydates:
var mydata;
fetch("{% static 'dates.json' %}")
.then(function(u){return u.json();})
.then(function(json){mydata = json; console.log(mydata)})
// test to see if mydates is correctly initialized, this should print in the console: 2018, 2019, 2020 ... not working
for (let year in mydata){
console.log(year)
}
我已阅读以下文章,但无济于事(我仍然难以理解如何解决它):
What is the scope of variables in JavaScript?
How do I return the response from an asynchronous call?
非常感谢您的帮助!
【问题讨论】:
-
将您的
for循环放入最后一个.then()回调。 -
这也可能有助于如何考虑回调:felix-kling.de/blog/2019/…
标签: javascript