我正在尝试在脚本中包含外部JSON文件:
var locations;
$.getJSON(themeUri + '/resources/location.json', function(result){
locations = result;
console.log(locations); // it shows right results.
});
console.log(locations); // undef
locations
不在全局范围内。如我所读,这是因为异步功能。
所以,我尝试了:
var locations;
function jsonCallback(result){
locations = result;
}
$.getJSON(themeUri + '/resources/location.json', jsonCallback);
也不起作用。如何将JSON内容放入全局变量中?
答案 0 :(得分:0)
第一个示例中的问题是console.log
发生在async
调用之前。
// 1. declaration happens
var locations;
// 3. this happens
$.getJSON(themeUri + '/resources/location.json', function(result){
locations = result;
console.log(locations); // it shows the right results.
});
// 2. console.log happens
console.log(locations); // undefined
因此2.
是未定义的,因为回调尚未发生。
可能的解决方案:
var locations;
function fillLocations(responseJSON) {
locations = responseJSON;
console.log(locations);
// Continue to next operation…
}
$.getJSON( 'https://jsonplaceholder.typicode.com/todos/1', function(result){
fillLocations(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>