ajax调用返回值,但变量为null
ajax call returns value but variable is null
我正试图从这里获得天气预报。这很好,我明白我的价值。如果我做一个普通的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'));
如果我通过这些函数进行调试,我会在success回调函数中得到好的结果,但强制转换变量为null,就像它从未被触摸过一样?
有人能给我解释一下吗?
问题。您的问题是,您从不调用本地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在请求期间不冻结。promise的使用使代码更加干净和全面。
您有两个不同的getWeatherForCity()
函数——一个是方法,另一个是私有函数(位于闭包内)。你从不调用私有函数,它实际上起作用。
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) {
getWeatherForCity(id); // here
var cast = value;
console.log(cast);
return cast;
};
}
您还可以研究$.when方法,该方法在继续之前等待Ajax调用完成:
http://api.jquery.com/jquery.when/
你会这样使用它:
$.when(getWeatherForCity([pass the parameter here])).done(function(){
// do stuff here after the method is finished
});
您还需要为Ajax函数使用返回,如下所示:
return $.ajax({
url: weatherUrl + id,
async: false,
success: function (data) {
console.log(data);
value = data;
}
});
相关文章:
- 来自文本输入null的html javascript变量
- 全局Javascript变量变为null
- 如何在JavaScript中检查变量是否为null和/或未定义
- Javascript将变量作为null传递
- 如果为null,则设置javascript变量的值
- 如果JS会话变量为null,如何避免500内部服务器错误
- 为什么 Javascript 在变量赋值时将 null 转换为字符串
- 使用clearInterval方法实现的是将区间变量引用设置为null,而不是
- 若字符串为null,则通过启发式方法无法访问代码,将null赋值给变量
- 从ajax到控制器返回的变量为null
- 在javascript中测试变量是否为null,而不会导致未定义的错误
- 检查 JS 变量是否不为 null 和 true
- Javascript 私有变量除非先设置为 null,否则不起作用
- 在 javascript 中访问 js 变量时无法读取 null 的属性“值”
- 这是检查变量是否被定义的最佳方法,而不是 null 并等于 “” 或其他任何内容
- 当变量的数据类型在 javascript 中为 'Null'
- 在 javascript 中声明变量时,默认值为 null
- 设置JavaScript变量= null,或者不定义
- 是否可以使用变量!= null而不是变量!== undefined &&== null
- Javascript变量null错误