2010-12-01 45 views
0

我想從JSON文件中獲取信息,但數據變量中沒有任何內容。任何人都可以告訴我我做錯了什麼。 JSON文件被下載,所以沒有問題,我沒有從服務器獲取任何東西。jQuery JSON獲取問題

function handle_geolocation_query(position) { 
    var url = "http://ws.geonames.org/findNearByWeatherJSON?lat=" + position.coords.latitude + "&lng=" + position.coords.longitude + "&callback=?"; 
    $.getJSON(url, function(info){ 
     var clouds = info.weatherObservation.clouds; 
     var weather = info.weatherObservation.weatherCondition; 
     var temp = info.weatherObservation.temperature; 
     var humidity = info.weatherObservation.humidity; 
    }); 
    //console.log(clouds); 
    document.getElementById('result').innerHTML = "C:" + clouds + ", W:" + weather + ", T:" + temp + ", H:" + humidity; 
} 

欣賞所有的幫助。 非常感謝。

+2

與螢火蟲可以檢查網面板,是回饋您正在訪問同一個結構上的JSON標籤的陣列。 – kobe 2010-12-01 05:55:25

+0

無論如何,你正在使用jQuery,使用.html()而不是.innerhtml,你可以simloy say('#result')。html();是weatherObservation一個對象或單個對象的數組。 – kobe 2010-12-01 05:56:29

回答

0

您應該嘗試將修改innerHTML的代碼放在回調中。記住JS有函數範圍。你不能在外面訪問這些變量。另外,這些變量只有在執行檢索JSON的回調後纔會設置。

function handle_geolocation_query(position) { 
    var url = "http://ws.geonames.org/findNearByWeatherJSON?lat=" + position.coords.latitude + "&lng=" + position.coords.longitude + "&callback=?"; 
    $.getJSON(url, function(info){ 
     var clouds = info.weatherObservation.clouds; 
     var weather = info.weatherObservation.weatherCondition; 
     var temp = info.weatherObservation.temperature; 
     var humidity = info.weatherObservation.humidity; 
     $('#result').html("C:" + clouds + ", W:" + weather + ", T:" + temp + ", H:" + humidity); 
    }); 
} 

編輯:繼GOV的建議,你應該使用jQuery的API的封裝HTML()方法,無論何時你發現需要改變的innerHTML。

此外,您還可以使用:

console.log(info); 

而在回調的getJSON調試只是爲了確保你的數據是結構化的,你覺得是這樣的。

0

嘗試做以下,我認爲這可能是未來爲對象

var clouds = info.weatherObservation.clouds; 
     var weather = info[0].weatherObservation.weatherCondition; 
     var temp = info[0].weatherObservation.temperature; 
     var humidity = info[0].weatherObservation.humidity;