迭代JSON数据和使用JQuery访问数据

时间:2011-07-31 23:52:57

标签: jquery ajax json

我有一个Web服务返回的以下JSON数据:

    {"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},
]}

我要做的是使用Jquery访问每个项目并将其推送到jGrowl通知中。我似乎无法通过alert数据的初始阶段:

$.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);
                }
            });

我知道这个问题很漂亮,但深夜帮助很感激:)

3 个答案:

答案 0 :(得分:3)

你的代码有点困惑。 1)你不需要使用parseJSON - jquery给你一个对象(msg),而不是json字符串 2)你检查msg ['d']的数组长度,然后尝试迭代msg,这是一个具有单个属性的对象(d)

此外,您不需要循环(通常很小的)jquery开销

var i = 0, size = msg['d'].length;
while (i < size) {
  alert(msg['d'][i]['AdvisoryMessage']);
  i++;
}

答案 1 :(得分:0)

我认为您正在尝试迭代数据,因为您正在解析msg.d并将其分配给数据变量。试试这个

var data = $.parseJSON(msg.d);

                        $.each(data, function() {
                            alert(msg.AdvisoryMessage);                                
                            $.jGrowl(msg.AdvisoryMessage, { sticky: true, theme: 'info' });

                        });

答案 2 :(得分:-1)

contentType: "application/json",

这是错误的。这是您发送时的内容类型,而不是您获得的内容类型。而且我非常怀疑你是在送json。

正如其他人提到的,你不需要$.parseJSON(msg.d) - 做dataType: 'json'已经导致它被解析。