2011-08-10 58 views
1

服務器返回給客戶端這個JSON:的Javascript JSON問題

{ 
    "comments": [ 
     { 
      "id": 99, 
      "entryId": 19, 
      "author": "Вася", 
      "body": "Комент Васи", 
      "date": "20.10.2022" 
     }, 
     { 
      "id": 100, 
      "entryId": 19, 
      "author": "n54", 
      "body": "w754", 
      "date": "21.10.2023" 
     } 
    ], 
    "admin": false 
} 

我試圖展現出它:

if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
    var json = eval("("+xmlhttp.responseText+")"); 
    for(var comment in json.comments){ 
     alert(comment["author"]); 
    } 
} 

正如預期的那樣,循環工程2倍,但這個警告只顯示「未定義」。 但是,如果我嘗試執行警報(json.admin);它會按計劃顯示錯誤。 我在做什麼錯?

+0

不要使用eval。永遠。使用JSON.parse。您可以使用Crockford的json2(https://github.com/douglascrockford/JSON-js/blob/master/json2.js)來實現跨瀏覽器兼容性。 –

回答

0

如果你有遍歷數組中的內容,你應該遍歷數組索引,而不是遍歷數組中的性能,

所以使用下面的代碼片段迭代這個數組索引是做正確的事,

for(var i = 0; i < json.comments.length; i++){ 
    alert(json.comments[i]["author"]); 
} 

遍歷如下面的代碼片段陣列屬性是不正確的做法,因爲陣列性能的一個包含「刪除」功能。

for(var i in json.comments){ 
    alert(json.comments[i]["author"]); 
} 

在上面的代碼將採取值0,1,2,...,除去功能

1

你需要做的

for(var comment in json.comments){ 
    alert(json.comments[comment]['author']); 
} 

評論只是即0的數組的索引,1

+0

非常感謝! – Twisty

0

試試這個

if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
    var json = eval("("+xmlhttp.responseText+")"); 
    for(var i=0;i<json.comments.length;i++){ 
     alert(comment[i].author); 
    } 
} 
0

在你的JSON評論是一個數組。這是更好的編號索引for循環。

if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
    var json = JSON.parse(xmlhttp.responseText); //See my comment on OP 
    for(var i = 0; i < json.comments.length; i++){ 
     alert(json.comments[i]["author"]); 
    } 
}