在 ajax 交互中,返回的 json 數據往往需要遍歷處理。本文總結了幾種常見的 jQuery 遍歷 json 的方法,包括 for 循環、for-in 以及 jQuery 的 each 方法。
ajax 請求中,返回的內容在 success 函數裡進行遍歷操作:
$.ajax({
url: '/path/to/file',
type: 'GET',
dataType: 'json',
data: {param1: 'value1'},
success: function (obj){
//遍歷obj
}
})
以如下 json 為例:
var obj = {
"status":1,
"bkmsg":"\u6210\u529f",
"bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u6dfb\u52a0\u8bb0\u5f55"]
}
for 循環:
if (obj.status == 1) {
for (var i = 0; i < obj.bkdata.length; i++) {
console.log(obj.bkdata[i]);
};
} else {
alert("數據有誤~");
};
for-in 循環:
for(x in obj.bkdata){
//x表示是下標
console.log(obj.bkdata[x]);
}
jQuery 的 each 方法:
if (obj.status == 1) {
$(obj.bkdata).each(function(index,item){
//index指下標,item指代對應元素內容,this指代每一個元素對象
console.log(item);
});
} else {
alert("數據有誤~");
}
//jquery each方法
$.each( obj.bkdata, function(index,item){
console.log(item);
});
三種方式各有側重:for 循環最直接、性能好;for-in 適合遍歷對象屬性;而 jQuery 的 each 方法寫法更為簡潔優雅,是處理數組與對象遍歷時的常用選擇。
希望本文所述對大家 jQuery 程序設計有所幫助。