Javascript JSON problem



服务器返回给客户端这个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次,但此警报只显示"未定义"。但如果我尝试执行alert(json。admin);它会像计划的那样显示错误。我做错了什么?

你需要做

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

comment是数组的索引即0,1

如果你必须遍历数组中的内容,你应该遍历数组的索引,而不是遍历数组中的属性,

那么使用下面的代码片段来遍历数组索引这是正确的做法,

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

像下面的代码片段一样遍历数组属性是不正确的,因为其中一个数组属性包含'remove'函数。

for(var i in json.comments){
    alert(json.comments[i]["author"]);
}
<<p>在上面的代码strong> 将值 0, 1, 2,…,删除函数

试试这个

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);
    }
}

在JSON中,comments是一个数组。最好使用编号索引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"]);
    }
}

最新更新