2014-10-29 56 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; 
     } 
    });