jquery - 为什么我的 jquery jsoneach() 循环返回未定义?

标签 jquery json

这是我的本地 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/

相关文章:

javascript - 在 Safari for Mac 中使用 Ctrl+Click 时如何禁用上下文菜单事件中的单击事件?

php - 如何在以逗号分隔的单个文本字段中使用多个关键字搜索 mysql 数据库列?

javascript - 如何在 Slack App 中将值从 Slack channel 传递到 `Options Load URL`

ruby - JSON 文本必须至少包含两个八位字节! (JSON::解析器错误)

javascript - 将类附加到 jQuery 对象

jquery 从链接打开 Accordion

javascript - 为 jQuery 中的现有类添加值

sql - 无法在 hive 中分解 json 字符串

javascript - Linq.js 子查询

php - 如何用 PHP 打印漂亮的 JSON