Javascript 正在更新全局变量:1。使用成员函数vs.2。使用AJAX回调函数 背景:
我正在构建一个简单的程序,该程序使用simplewather.js API获取程序其余部分()使用的当前温度 更新代码: 以下所有代码都在AngularJS控制器中,SimpleWather.js文件链接在index.html文件中Javascript 正在更新全局变量:1。使用成员函数vs.2。使用AJAX回调函数 背景:,javascript,jquery,scope,jquery-callback,weather-api,Javascript,Jquery,Scope,Jquery Callback,Weather Api,我正在构建一个简单的程序,该程序使用simplewather.js API获取程序其余部分()使用的当前温度 更新代码: 以下所有代码都在AngularJS控制器中,SimpleWather.js文件链接在index.html文件中 var _this = this; var seasons = null; function myAjaxCheck(callBack){ $.simpleWeather({ location: 'Calgary,
var _this = this;
var seasons = null;
function myAjaxCheck(callBack){
$.simpleWeather({
location: 'Calgary, CA',
woeid: '',
unit: 'c',
success: function(weather) {
var temperatureTemp = parseInt(weather.temp);
callBack(temperatureTemp);
}
});
}
var temperature;
myAjaxCheck(function(returnedTemperature){
temperature = returnedTemperature;
if (temperature > 20){
_this.seasons = summerCollection; <-- summerCollection is an array strings
}
});
更新:问题:
似乎我可以用第二段代码中的成员函数test()更新全局变量。但是,为什么在第一段代码中没有使用AJAX回调函数更新全局变量
我的HTML中有一个div,它使用ng repeat吐出summerCollection数组中的所有字符串。
它适用于第二段代码,但不适用于第一段代码
非常感谢您的帮助
有什么想法吗
原始问题:
从我从web检查器收集的信息来看,此代码的加载顺序似乎是(不应该是):
a、 美元。SimpleWither({
b、 警报(温度)
c、 成功:功能(天气){
知道为什么吗?我知道如果我在success:function(weather){}中输入alert(temperature),它会返回当前的温度,但这不是我想要的
我最终希望变量温度保持当前温度,以便在其他函数中使用此变量。例如,我希望能够根据温度值将“季节”设置为不同的字符串
非常感谢您的帮助!这就是回调的本质-它们是异步的。代码应该按照您描述的顺序运行 您所做的是正确的,只是警报在回调完成之前运行(应该如此) 因此,您需要做的是将您的警报(以及您想要运行的真实代码)放入回调:
var temperature = null; <-- this variable should store the temperature retrieved by simpleWeather API
var seasons = null;
$.simpleWeather({
location: 'Calgary, CA',
woeid: '',
unit: 'c',
success: function(weather) {
temperature = parseInt(weather.temp); <-- Temperature variable defined outside this scope
alert(temperature);
// call your remaining code here, which will run after the temperature has been set.
some_other_function();
}
});
function some_other_function() {
}
var-temperature=null;感谢您的建议。我尝试过实现此功能,但遇到了一个新问题。我更新了问题,您介意看一看并告诉我您的想法吗?谢谢您将console.log(returnedTemperature)作为回调的第一行(在设置全局值之前),它是否显示正确的温度?是的,它显示正确的温度
var temperature = null; <-- this variable should store the temperature retrieved by simpleWeather API
var seasons = null;
$.simpleWeather({
location: 'Calgary, CA',
woeid: '',
unit: 'c',
success: function(weather) {
temperature = parseInt(weather.temp); <-- Temperature variable defined outside this scope
alert(temperature);
// call your remaining code here, which will run after the temperature has been set.
some_other_function();
}
});
function some_other_function() {
}