为什么我的jquery json each()循环返回undefined?

时间:2012-10-08 12:37:10

标签: jquery json

这是我在Jsonlint验证的本地Json。

{
"messages": {
    "count": "0",
    "items": [
        {
            "MessageID": "1",
            "Starred": 0,
            "BodyPrev": "You wouldn't believe what has just happenedYou wouldn't believe what has ",
            "FromUserID": "1",
            "FromName": "Daisy Purdye",
            "FromUN": "daisypurdye",
            "Subject": "Yeayeah",
            "Body": "You wouldn't believe what has just happenedYou wouldn't believe what has just happenedYou wouldn't believe what has just happenedYou wouldn't believe what has just happenedYou wouldn't believe what has just happenedYou wouldn't believe what has just happened",
            "Ctime": "10/4/2012",
            "isRead": "1"
        },
        {
            "MessageID": "2",
            "Starred": 1,
            "BodyPrev": "Whatever",
            "FromUserID": "1",
            "FromName": "Daisy Purdye",
            "FromUN": "daisypurdye",
            "Subject": "Not true mate",
            "Body": "Whatever",
            "Ctime": "5/3/2012",
            "isRead": "1"
        }
    ]
}

}

这里是用于打印消息的jQuery ......

    <script>
    $.getJSON("/json/messages.json",function(result){
        $.each(result, function(i, messages){
            console.log(messages.items.Subject)
        });
      });
   </script>

它只是返回undefined。

6 个答案:

答案 0 :(得分:5)

$.each应该接收一个数组,然后将根对象传递给它,这不是数组,因为您的消息数组位于result.messages.items

要迭代消息,您应该

  $.getJSON("/json/messages.json",function(result){
    $.each(result.messages.items, function(i, message){
        console.log(message.Subject)
    });
  });

答案 1 :(得分:0)

项目本身就是一个数组,所以我猜你至少需要访问它,如:

messages.items[0].Subject

答案 2 :(得分:0)

项目是一个数组。你应该遍历它以获得所有项目。

 <script>
    $.getJSON("/json/messages.json",function(result){
        $.each(result, function(i, messages){
          $.each(messages.items, function(index, item){
                 console.log(item.Subject)
           });

        });
      });
   </script>

答案 3 :(得分:0)

items属性是一个数组,因此您无法使用items.Subject

循环遍历数组中的项目,而不是循环遍历根对象中的属性:

$.getJSON("/json/messages.json",function(result){
  $.each(result.messages.items, function(i, item){
    console.log(item.Subject)
  });
});

答案 4 :(得分:0)

逻辑上似乎存在问题。试试这个:

<script>
        $.getJSON("/json/messages.json",function(result){
            $.each(result.items, function(i, item){
                console.log(item.Subject)
            });
          });
       </script>

答案 5 :(得分:0)

您的对象以此形式存在

MainObj---> messages -----> items---->Subject

因此,如果您需要打印主题,则必须以与它们相同的方式访问

result.messages.items.Subject