jquery $.each()遍历json数组
使用jQuery的$.each()方法来遍历一个数组对象
var json=[
{"id":"1","tagName":"apple"},
{"id":"2","tagName":"banana"},
{"id":"3","tagName":"orange"},
{"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":"banana"},
{"id":"3","tagName":"orange"},
{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';
$.each(json,function(idx,obj){alert(obj.tagNmae);});
所以如果声明的是字符串,那么便遍历的时候应该先用json.parse()或者jquery的方法$.parseJSON将字符串转化为JavaScript对象
$.each(JSON.parse(json),function(idx,obj)
{alert(obj.tagNmae);
});
或者
$.each(JSON.parse(json),function(idx,obj)
{alert(obj.tagNmae);
});