javascript 如何遍历json格式数据?

varjsn=[{"Id":14,"Name":"政治","ParentId":0},{"Id":15,"Name":"法律","ParentId":0},{"Id":1... var jsn=
[{"Id":14,"Name":"政治","ParentId":0},{"Id":15,"Name":"法律","ParentId":0},{"Id":16,"Name":"科技","ParentId":0},{"Id":17,"Name":"娱乐","ParentId":0},{"Id":18,"Name":"时尚","ParentId":0},{"Id":19,"Name":"旅游","ParentId":0},{"Id":20,"Name":"教育","ParentId":0},{"Id":21,"Name":"环保","ParentId":0},{"Id":22,"Name":"社会","ParentId":0},{"Id":23,"Name":"心理","ParentId":0},{"Id":24,"Name":"中医","ParentId":0},{"Id":25,"Name":"西医","ParentId":0},{"Id":26,"Name":"社交","ParentId":0},{"Id":27,"Name":"IT","ParentId":0},{"Id":28,"Name":"汽车","ParentId":0}]
展开
 我来答
yongirl320
2012-02-29 · TA获得超过830个赞
知道小有建树答主
回答量:280
采纳率:100%
帮助的人:481万
展开全部
<script type="text/javascript">

var jsn=
[{"Id":14,"Name":"政治","ParentId":0},{"Id":15,"Name":"法律","ParentId":0},{"Id":16,"Name":"科技","ParentId":0},{"Id":17,"Name":"娱乐","ParentId":0},{"Id":18,"Name":"时尚","ParentId":0},{"Id":19,"Name":"旅游","ParentId":0},{"Id":20,"Name":"教育","ParentId":0},{"Id":21,"Name":"环保","ParentId":0},{"Id":22,"Name":"社会","ParentId":0},{"Id":23,"Name":"心理","ParentId":0},{"Id":24,"Name":"中医","ParentId":0},{"Id":25,"Name":"西医","ParentId":0},{"Id":26,"Name":"社交","ParentId":0},{"Id":27,"Name":"IT","ParentId":0},{"Id":28,"Name":"汽车","ParentId":0}];

document.write('<table border="1">');
document.write('<tr>');
document.write('<td>id</td>');
document.write('<td>name</td>');
document.write('<td>parentid</td>');
document.write('</tr>');

var len = jsn.length;
for(var i=0;i<len;i++) {
document.write('<tr>');
document.write('<td>'+jsn[i]['Id']+'</td>');
document.write('<td>'+jsn[i]['Name']+'</td>');
document.write('<td>'+jsn[i]['ParentId']+'</td>');
document.write('</tr>');
}

document.write('</table>');

</script>
追问
$(function () {
$.post("GetSysCate.aspx", "Id=0", function (jsn) {
document.write(jsn);
});
});
我这样输出的就是:
[{"Id":16,"Name":"科技","ParentId":0},{"Id":27,"Name":"IT","ParentId":0},{"Id":28,"Name":"汽车","ParentId":0}]这样格式的
但是我用你上面的方法输出时全是未定义,怎样遍历服务器传来的data?
data 是序列化的List
Category类有三个字段
追答
是因为你 输出时候的 jsn是 JSON格式的 字符串而已,所以才出现这个问题,

你先把 jsn 转换成 实际的 对象, 加上一句话就行,

var jsn = eval(jsn);

然后在用我给的 代码就行了。
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式