1

这是我在 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>

它只是返回未定义。

4

6 回答 6

5

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

要遍历消息,您应该这样做

  $.getJSON("/json/messages.json",function(result){
    $.each(result.messages.items, function(i, message){
        console.log(message.Subject)
    });
  });
于 2012-10-08T12:39:00.763 回答
0

Items 本身就是一个数组,所以我猜你至少需要像这样访问它:

messages.items[0].Subject
于 2012-10-08T12:39:21.473 回答
0

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

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

        });
      });
   </script>
于 2012-10-08T12:39:47.933 回答
0

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

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

$.getJSON("/json/messages.json",function(result){
  $.each(result.messages.items, function(i, item){
    console.log(item.Subject)
  });
});
于 2012-10-08T12:41:17.083 回答
0

好像逻辑有问题。试试这个:

<script>
        $.getJSON("/json/messages.json",function(result){
            $.each(result.items, function(i, item){
                console.log(item.Subject)
            });
          });
       </script>
于 2012-10-08T12:42:09.877 回答
0

您的对象以这种形式存在

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

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

result.messages.items.Subject
于 2012-10-08T12:46:31.460 回答