这是我的本地 Json,它正在 Jsonlint 中进行验证。
{
"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)
});
});
关于jquery - 为什么我的 jquery jsoneach() 循环返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12781901/