2010-07-12 57 views
0

在下面的代碼中,我嘗試遍歷JSON對象字符串。但是,我沒有得到所需的輸出。我的網頁上輸出看起來是這樣的: -通過遍歷JSON對象迭代的問題

+ item.temperature ++ item.temperature ++ item.temperature ++ item.temperature +

輸出溫度警報效果很好。我嘗試通過遍歷JSON對象字符串來訪問值的部分似乎不起作用。有人能幫我解決這個問題嗎?

代碼

<body> 

<script> 

$.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2', 
function(data) { 

      $.each(data.weatherObservations, function(i,item){ 
      $("body").append("+item.temperature+"); 
      if (i == 3) return false; 
      }); 
    alert(data.weatherObservations[0].temperature); 
     }); 

</script> 

</body> 

回答

3

不要在.append()部分內$("body").append("+item.temperature+");使用引號。

應該

$(document.body).append(item.temperature); 

書面方式加上引號像你這樣的表達,只是一遍又一遍地增加了string。 Java // Ecmascript將帶引號的任何內容解釋爲字符串文字。

請注意,我也用document.body替換"body"。這主要是表現/ /訪問的原因,所以更好的業力。

1

你的代碼是通過迭代,但要追加 「+ item.temperature +」,你不想做這樣的事情

$("body").append("Temp is " + item.temperature); 

$("body").append(item.temperature); 
0

"+item.temperature+"意味着一個字符串這是"+item.temperature+"

"pre" + item.temperature + "post"將連接變量到字符串。

$.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2', 
    function (data) { 
    $.each(data.weatherObservations, function (i, item) { 
     $("body").append(item.temperature + ","); 
     if (i == 3) return false; 
    }); 
    alert(data.weatherObservations[0].temperature); 
});