Iterative JSON data and accessing the data with JQuery
I have the following JSON data being returned by a webservice:
{"d":[
{"RelationshipManager":{},"AdvisoryId":13,"ClientId":22,"UserId":13,"AdvisoryMessage":"Welcome!","Seen":false,"Issued":"\/Date(1312123970110)\/","Delivered":null,"Importance":3},
{"RelationshipManager":{},"AdvisoryId":14,"ClientId":22,"UserId":13,"AdvisoryMessage":"A really long boring message.","Seen":false,"Issued":"\/Date(1312123970113)\/","Delivered":null,"Importance":1},
{"RelationshipManager":{},"AdvisoryId":15,"ClientId":22,"UserId":13,"AdvisoryMessage":"Another really long boring message.","Seen":false,"Issued":"\/Date(1312123970113)\/","Delivered":null,"Importance":1},
]}
What I'm trying to do is access each item using Jquery and push this into a jGrowl notification. I can't seem to get passed the initial phase of alert
ing the data out:
$.ajax({
type: "POST",
url: "http://xxx/Service/Assets.asmx/GetUnreadAdvisories",
data: "{'sessionHash':'<%=Session["SessionHash"].ToString()%>'}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
if (msg["d"].length > 0) {
var data = $.parseJSON(msg.d);
$.each(msg, function() {
alert(msg.AdvisoryMessage);
$.jGrowl(msg.AdvisoryMessage, { sticky: true, theme: 'info' });
})
} else {
alert('no fish');
return false;
}
},
error: function (msg) {
alert(msg);
开发者_如何学Go }
});
I know this question is pretty noob, but late night help is appreciated :)
Your code is a little confused. 1) you don't need to use parseJSON - jquery is giving you an object (msg), not the json string 2) you check the array length of msg['d'] but then try and iterate through msg, which is an object with a single property (d)
Also, you don't need the (admittedly small) jquery overhead for your loop
var i = 0, size = msg['d'].length;
while (i < size) {
alert(msg['d'][i]['AdvisoryMessage']);
i++;
}
I think you are trying to iterate through data since you are parsing msg.d and assigning it to data variable. Try this
var data = $.parseJSON(msg.d);
$.each(data, function() {
alert(msg.AdvisoryMessage);
$.jGrowl(msg.AdvisoryMessage, { sticky: true, theme: 'info' });
});
contentType: "application/json",
This is wrong. This is the content type of when you are sending not what you are getting. And I highly doubt you are sending json.
And as someone else mentioned, you don't need to $.parseJSON(msg.d)
- doing dataType: 'json'
already causes it to be parsed.
精彩评论