javascript - 将 javascript 变量升级到全局范围
问题描述
我正在尝试在脚本中包含一个外部 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 内容放入全局变量中?
解决方案
您最初示例中的问题是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>
推荐阅读
- python - Pandas 数据框到 dict,同时保留重复的行
- reactjs - React Native + React Native Keychain + Jest:如何正确模拟 React Native Keychain?
- spring - 使用 Hibernate seesion.delete() 的更好方法是按 ID 删除还是按对象删除?
- php - 使用 PHP 5.3.8 进行调试
- excel - Excel VBA 代码无法在某些计算机上运行
- python - MQTT Python-Client 异常断开连接
- r - 使用调用函数B的R的函数A如何定义B的参数
- ios - Swift 4:UISearchBar 和 NavigationBar
- zipkin - 使用tomcat服务器而不使用配置文件的zipkin勇敢实现
- jquery - 如何根据子div值隐藏对应的父div