我试图从一个JSON源获取特定数据段。我已经声明了一个全局变量并尝试更新全局变量,但它没有正确更新。此外,我的调试警报运行顺序令人困惑。混淆JavaScript的全局变量范围和更新
<script>
//global variable
var latestDoorStatus = "initialized value"; //set value for debugging purposes
//debug alert which also calls the function
alert("Alert#1: call getDoorStatus = " + getDoorStatus("***********"));
function getDoorStatus(public_key) {
//get data in json form
var cloud_url = 'https://data.sparkfun.com/output/';
// JSONP request
var jsonData = $.ajax({
url: cloud_url + public_key + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
var latest = results[0];
//debug alert
alert("Alert #2: latestDoorStatus = " + latestDoorStatus);
//update the global variable
latestDoorStatus = latest.doorstatus;
//debug alert
alert("Alert #3: latestDoorStatus = " + latestDoorStatus);
//return the global variable
return latestDoorStatus;
});
alert("Alert #4: latestDoorStatus = " + latestDoorStatus);
}
</script>
当我在浏览器中运行这个,我得到了以下行为:
首先,我得到警报#4(应该在脚本运行结束)与全局变量的初始化值
然后我得到警报#1为“不确定”。这应该是调用函数getDoorStatus的结果应该返回latestDoorStatus
的更新值然后我得到警报#2 latestDoorStatus的初始化值,因为全局变量尚未更新,这是有道理的
然后我得到警报#3的功能应该返回变量latestDoorStatus后警报#3(即在全局变量是否已正确更新),所以我不明白为什么警报#latestDoorStatus
的正确值1(这是应该有返回值)回来不确定,为什么警报#4这是应该在S的最后运行cript正在运行。
你应该看看(http://stackoverflow.com/questions/14220321/how-do-i-return-the-a-an-asynchronous-call),我想你也有同样的问题。 – Volune