2014-10-29 52 views
1

我试图从here得到天气预报。这工作正常,我得到了我的价值。如果我做一个正常的Ajax调用它工作正常。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')); 

如果我通过这些功能的调试,我得到了很好的结果,成功的回调函数里面,但投变量为空,喜欢它从未被感动过?

有人可以向我解释吗?

+3

让我们开始吧wi “async:false”这个事实是非常糟糕的,并且是不赞成的事情。 – Regent 2014-10-29 07:55:26

+0

好吧,我知道,但这不是真的答案。 – Ipad 2014-10-29 07:56:21

+1

问题是,你从来没有真正调用'getWeatherForCity()'。因此,结果。 – dfsq 2014-10-29 07:59:37

回答

2

问题。你的问题是,你永远不会拨打本地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的使用使得代码更加清晰和更全面。

+0

谢谢,是的,我知道,但我尝试了一点点!谢谢你的帮助。我会立即删除它 – Ipad 2014-10-29 08:06:33

+0

我认为它更好地删除私人函数本身,并做你在方法中做的事情。为什么要创建一个不必要的私人功能.. – bipen 2014-10-29 08:10:26

+0

@bipen也许你是对的。这取决于一些因素。 OP可能需要一些额外的处理。但是,如果没有,那么是的,它可以被删除。 – dfsq 2014-10-29 09:50:55

1

你有两个不同的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; 

    }; 
} 
+0

啊,当然我是愚蠢的!谢谢! :-) – Ipad 2014-10-29 08:05:33

0

你也可以看看到$。当方法,它等待一个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; 
     } 
    });