2012-10-08 47 views
1

这是我在Jsonlint验证的本地Json。为什么我的jquery json each()循环返回undefined?

{ 
"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。

回答

4

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

遍历的消息,你应该做的

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

优秀的存在, 谢谢。这是我疲惫的心灵可能整天看着它,仍然没有看到明显的那些问题之一:D这是非常有道理的。当我被允许时,我会在几分钟内接受答案。 –

0

项目本身是一个数组,以便即时猜测你至少需要访问它想:

messages.items[0].Subject 
0

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

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

     }); 
     }); 
    </script> 
0

items属性是一个数组,这样你就不能使用items.Subject

循环通过阵列中的项目,而不是通过在根对象的属性循环,:

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

似乎存在与所述逻辑的问题。试试这个:

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

你的对象以这种形式

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

所以如果你需要打印的主题,那么你必须以同样的方式来访问,因为他们存在

result.messages.items.Subject