Extract some parts of JSON objects result
I'm trying to parse JSON result from an Ajax call to .NET web service like the following:
function doAjaxCallBack() {
$.ajax({
type: "POST",
url: "AjaxCallBackService.asmx/GetAllTitles",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// show alert book title and tags to test JSON result
},
});
}
Here's the JSON result I got back from doAjaxCallBack:
{"d":[
{
"__type":"ASP.NET_Traini开发者_开发知识库ng.Book",
"Price":12.3,
"Title":"Javascript Programming",
"Tag":["Ajax","Javascript"]
},
{
"__type":"ASP.NET_Training.Book",
"Price":14.23,
"Title":"Code Complete",
"Tag":["Programming","Concept"]
}
]}
I want to get book title and its tags. How do I loop over this kind of JSON?
Thank you.
You're getting back an Object with one property d
, which references an Array of objects.
You can use the jQuery.each()
[docs] method to iterate over that Array, and select the Title and Tag properties from each Object in the Array.
$.each(msg.d, function( i, val ) {
console.log(val.Title);
$.each(val.Tag, function( i, val ) {
console.log("Tag: " + val);
});
});
Live Example: http://jsfiddle.net/emSXt/3/ (open your console)
$.each(msg.d, function( i, value ) {
console.log(value.Title);
if($.isArray(value.Tag)) {
$.each(value.Tag, function(j, value1) {
console.log(value1);
});
}else {
console.log(value.Tag);
}
});
Here's a fiddle http://jsfiddle.net/ATBNx/
for(var ib in msg.d) {
alert(msg.d[ib].Title);
for(var it in msg.d[ib].Tag) {
alert(msg.d[ib].Tag[it]);
}
}
精彩评论