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

 

先来一段简单的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);
});

 

 

 

posted @ 2016-01-15 11:32  Web前端架构  阅读(634)  评论(0编辑  收藏  举报