这是我在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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
}
这是jQuery来打印出消息...
<script>
$.getJSON("/json/messages.json",function(result){
$.each(result, function(i, messages){
console.log(messages.items.Subject)
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
它只是返回未定义。
$.each应该会收到一个数组,然后将根对象(不是数组)传递给它,因为您的消息数组位于中result.messages.items。
要遍历消息,您应该
$.getJSON("/json/messages.json",function(result){
$.each(result.messages.items, function(i, message){
console.log(message.Subject)
});
});
Run Code Online (Sandbox Code Playgroud)