【发布时间】:2017-05-14 22:21:46
【问题描述】:
所以我的 JSON 有问题。它给我一个未定义的。 奇怪的是它识别出我的第一个变量。
这里有代码来说明清楚。
JSON
{"Comics":[
{"comic" :
{
"src":"Pictures/Comics/dw.jpg",
"descr":"Doctor Who has a nice tv show."
}
},
{"comic" :
{
"src":"Pictures/Comics/spi.jpg",
"descr":"Spider man is a nice comic \
The main spider-man comic \
ended with Peter Parker's \
death."
}
},
{"comic" :
{
"src":"Pictures/Comics/gg.jpg",
"descr":"Power puff girls also has a \
nice tv show . \
You should try watching it."
}
},
{"comic" :
{
"src":"Pictures/Comics/v.jpg",
"descr":"V fo Vendeta is a nice \
graphical volume written by\
Allan Moor who also wrote \
Watchmen. Those books had a movie."
}
}
]
}
这是我的 Javascript
var arrI = new Array(4);
var arrD = new Array(4);
var x = new XMLHttpRequest;
x.onload = function(){
if(x.status == 200){
var txt = JSON.parse(x.responseText);
for(var g = 0; g<txt.Comics.length; g++){
arrI[g] = txt.Comics[g].comic.src;
arrD[g] = txt.Comics[g].comic.descr;
alert(arrD[g]);
}
}
}
x.open("GET",'Ajax/ImgCom.json', true);
x.send(null);
奇怪的是arrI[g] = txt.Comics[g].comic.src; 没问题。如果我提醒它,它会给我src。但desc 不是。它提醒我undefined。我不明白为什么,毕竟他们都有好路。
我试图用https://jsonlint.com 纠正自己。 它告诉我:
Error: Parse error on line 5:
....jpg", "descr": 'Doctor Who has a ni
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
然后我尝试将 desc 的 " 更改为 ',但没有成功。
最后,我也尝试了...=txt.Comics[g].comic[desc] 表示法,但它仍然给 e undefined。
我更正了自己,我没有发现任何错字。也许有。
感谢您的宝贵时间。
【问题讨论】:
-
从你的 json 中删除 \
-
您是如何生成 JSON 的?您应该在自己喜欢的环境中使用标准 JSON 编码函数。永远不要尝试自己生成 JSON。
标签: javascript arrays json ajax