一、$.each遍历json对象
查看一个简单的jQuery的例子来遍历一个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(i, obj) {
alert(obj.tagName);
});
上面的代码片断工作正常,提示 “apple”, “orange” … 等,如预期一样。
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(i, obj) {
alert(obj.tagName);
});
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(i, obj) {
alert(obj.tagName);
});
//or
$.each($.parseJSON(json), function(i, obj) {
alert(obj.tagName);
});
var json1={
"abc":[
{"name":"txt1"},
{"name","txt2"}
]
};
以上遍历的方法是:
for(var i=0;i
var json2={"name":"txt1","name2":"txt2"};
json本身没有length属性,所以用length属性自然会出错。
for(var i=0;i
以上脚本执行时,将会出错。
for(var js2 in json2){
alert( js2 + "=" + json2[js2]);
}
var jslength=0;
for(var js2 in json2){
jslength++;
}
function getJsonLength(jsonData){
var jsonLength = 0;
for(var item in jsonData){
jsonLength++;
}
return jsonLength;
}