Javascript JSON问题
服务器将此JSON返回给客户端:Javascript JSON问题,javascript,ajax,json,foreach,cycle,Javascript,Ajax,Json,Foreach,Cycle,服务器将此JSON返回给客户端: { "comments": [ { "id": 99, "entryId": 19, "author": "Вася", "body": "Комент Васи", "date": "20.10.2022" }, { "id": 100,
{
"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);它将按计划显示为false。
我做错了什么?你需要做什么
for(var comment in json.comments){
alert(json.comments[comment]['author']);
}
comment只是数组的索引,即你需要执行的0,1
for(var comment in json.comments){
alert(json.comments[comment]['author']);
}
comment只是数组的索引,即0,1
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);
}
}
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var json=eval(“+xmlhttp.responseText+”);
对于(var i=0;i试试这个
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);
}
}
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var json=eval(“+xmlhttp.responseText+”);
对于JSON中的(var i=0;i,注释是一个数组。最好使用编号索引循环
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"]);
}
}
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var json=json.parse(xmlhttp.responseText);//请参阅我对OP的评论
for(var i=0;i
在JSON中,注释是一个数组。最好使用编号索引循环使用
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"]);
}
}
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var json=json.parse(xmlhttp.responseText);//请参阅我对OP的评论
for(var i=0;i
如果必须迭代数组中的内容,则应迭代数组索引,而不是迭代数组中的属性
因此,使用下面的代码段迭代数组索引,这是正确的做法
for(var i = 0; i < json.comments.length; i++){
alert(json.comments[i]["author"]);
}
在上面的代码中,i将取值0,1,2,…,删除函数如果必须迭代数组中的内容,则应迭代数组索引,而不是迭代数组中的属性
因此,使用下面的代码段迭代数组索引,这是正确的做法
for(var i = 0; i < json.comments.length; i++){
alert(json.comments[i]["author"]);
}
在上面的代码中,i将取值0、1、2,…,删除函数不要使用eval.Ever。使用JSON.parse。可以使用Crockford的json2()实现跨浏览器兼容性。不要使用eval.Ever。使用JSON.parse。可以使用Crockford的json2()实现跨浏览器兼容性。