这是我在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>
它只是返回未定义。
最佳答案
$.each
应该接收一个数组,并且您将根对象(不是数组)传递给它,因为您的消息数组在result.messages.items
中。
要遍历消息,您应该
$.getJSON("/json/messages.json",function(result){
$.each(result.messages.items, function(i, message){
console.log(message.Subject)
});
});