jQuery's method of traversing json Recommended by of

  • 2021-06-28 10:36:51
  • OfStack


var obj = {"status":1,"bkmsg":"\u6210\u529f","bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u6dfb\u52a0\u8bb0\u5f55"]}{"status":1,"bkmsg":"\u6210\u529f","bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u6dfb\u52a0\u8bb0\u5f55"]},{"status":1,"bkmsg":"\u6210\u529f","bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u4ec0\u4e48\u4e5f\u6ca1\u6709"]} 

ajax request:


$.ajax({ 
url: '/path/to/file', 
type: 'GET', 
dataType: 'json', 
data: {param1: 'value1'}, 
success: function (obj){ 
// ergodic obj 
} 
}) 

What is returned is inside the success function, where all traversal operations operate:

for cycle:


var obj = { 
"status":1, 
"bkmsg":"\u6210\u529f", 
"bkdata":["\u5415\u5c1a\u5fd7","1387580400","\u6dfb\u52a0\u8bb0\u5f55"] 
} 
// console.log(obj.length); 
if (obj.status == 1) { 
for (var i = 0; i < obj.bkdata.length; i++) { 
console.log(obj.bkdata[i]); 
}; 
}else{ 
alert(" Data Error ~"); 
}; 

for in cycle:


//for in loop  
for(x in obj.bkdata){ 
//x Representation is a subscript to specify a variable that can be an array element or an object's attribute.  
console.log(obj.bkdata[x]); 
} 
// element  each Method 
if (obj.status == 1) { 
$(obj.bkdata).each(function(index,item){ 
//index Indicate Subscript  
//item Reference to corresponding element content  
//this Refers to every 1 Element Objects  
//console.log(obj.bkdata[index]); 
console.log(item); 
//console.log($(this)); 
}); 
}else{ 
alert(" Data Error ~"); 
}; 
//jquery each Method 
$.each( obj.bkdata, function(index,item){ 
console.log(item); 
}); 

ajax for jQuery and the code for traversing the json array are as follows:


jQuery.ajax({ 
type: "POST", 
url: "server.json", 
dataType:'json', 
data: "", 
success: function(msg){ 
var title = ""; 
jQuery.each(msg,function(key,value){ 
alert(value.ec_id+" "+value.ec_title); 
}) 
} 
});


Related articles: