服務器返回給客戶端這個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);它會按計劃顯示錯誤。 我在做什麼錯?
不要使用eval。永遠。使用JSON.parse。您可以使用Crockford的json2(https://github.com/douglascrockford/JSON-js/blob/master/json2.js)來實現跨瀏覽器兼容性。 –