码迷,mamicode.com
首页 > Web开发 > 详细

jQuery loop over JSON字符串 – $.each实例

时间:2016-01-15 12:58:11      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

 

先来一段简单的javascript对象的遍历:

 


var json = [
    {"id":"1","tagName":"apple"},
    {"id":"2","tagName":"orange"},
    {"id":"3","tagName":"banana"},
    {"id":"4","tagName":"watermelon"},
    {"id":"5","tagName":"pineapple"}
];

$.each(json, function(idx, obj) {
    alert(obj.tagName);
});

 


当为JSON字符串时:

var json = ‘[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}];
    
$.each(json, function(idx, obj) {
    alert(obj.tagName);
});

 


在Chrome中,他会显示 错误:
Uncaught TypeError: Cannot use ‘in‘ operator to search for ‘156‘ 
in [{"id":"1","tagName":"apple"}...

 



解决方案:
var json = ‘[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}];
    
$.each(JSON.parse(json), function(idx, obj) {
    alert(obj.tagName);
});

//or 

$.each($.parseJSON(json), function(idx, obj) {
    alert(obj.tagName);
});

 

 

 

jQuery loop over JSON字符串 – $.each实例

标签:

原文地址:http://www.cnblogs.com/Web-Architecture/p/5132812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!