我正在尝试从 here 获取天气预报.这工作正常,我得到了我的值(value)。如果我做一个普通的 ajax 调用,它工作正常。
但是:
function Weather() {
var self = this,
weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?id=',
value = null;
function getWeatherForCity(id) {
$.ajax({
url: weatherUrl + id,
async: false,
success: function (data) {
console.log(data);
value = data;
}
});
}
self.getWeatherForCity = function (id) {
var cast = value;
console.log(cast);
return cast;
};
}
电话:
weather = new Weather();
console.log(weather.getWeatherForCity('2878234'));
如果我通过这些函数进行调试,我会在成功回调函数中得到好的结果,但是转换变量为空,就像它从未被触及过一样?
有人能给我解释一下吗?
最佳答案
问题。你的问题是你从不调用本地 getWeatherForCity
函数。所以它永远不会改变 value
变量。这应该修复它:
self.getWeatherForCity = function (id) {
getWeatherForCity(id);
return value;
};
更好的方法。看起来您已经意识到使用 async: false
并不是理想的解决方案。在这种情况下,我会建议您更好的选择。
function Weather() {
var self = this,
weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?id=';
function getWeatherForCity(id) {
return $.get(weatherUrl + id);
}
self.getWeatherForCity = function (id) {
return getWeatherForCity(id);
};
}
var weather = new Weather();
weather.getWeatherForCity('2878234').then(function(data) {
console.log(data);
});
使用异步代码使 UI 在请求期间不卡住。使用 promises 使代码更简洁、更全面。
关于javascript - ajax 调用返回值但变量为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26625193/