2013-10-04 61 views
-2

我想通過第一次循環json對象,我想要做的就是列出所有的temp變量的內容,但我無法計算如何循環工作。通過使用jQuery的JSON循環

$("button").click(function(){ 
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=53.7&lon=0.3&callback=?" ; 
$.getJSON(url, function(res) { 

    $('#result').html('<p>lon: ' + res.city.coord.lon + '</p>'); 
    $('#result').append('<p>lat: ' + res.city.coord.lat + '</p>'); 
    $('#result').append('<p>wind: ' + res.wind.speed + '</p>'); 

     $.each(res.list.main, function(i, temp) { 
      $('#result').append('<p>temp: ' + temp[i] + '</p>'); 
     }); 
}); 

});

+7

'temp'是值,不需要括號'[]' –

+0

你試圖確定你的$ .each回調期間發生了什麼? –

回答

1

你應該真的console.log你的對象,並找出結構。

該對象在您認爲的位置沒有res.wind.speed

這裏是您的對象的概覽 - >http://jsfiddle.net/t2KMk/1/

通知,list是不同時間包含這樣的事情,風,雲,雨,主等

等對象的數組

這裏有一個如何遍歷這些值,得到了風

$("button").click(function(){ 
    var url = "http://api.openweathermap.org/data/2.5/forecast?lat=53.7&lon=0.3&callback=?"; 

    $.getJSON(url, function(res) { 
     $('#result').html('<p>lon: ' + res.city.coord.lon + '</p>'); 
     $('#result').append('<p>lat: ' + res.city.coord.lat + '</p>'); 

     $.each(res.list, function(i, temp) { // iterate the array 

      $('#result').append('<p>wind: ' + temp.wind.speed + '</p>'); 
            //    ^^^ here you have wind 
     }); 
    }); 
}); 

爲例