0

目前第一次使用 JSON 并且没有 jQuery 经验。我有这个函数在 $.ajax 请求的“成功”时触发:

function(data) {

    $.each(data.notifications, function(notifications) {
        alert('New Notification!');
    });

}

但是,我在萤火虫控制台中收到一个错误,指出“对象未定义”“长度 = object.length”。

JSON 响应是:

["notifications",[["test would like to connect with you",{"Accept":"\/events\/index.php\/user\/connection?userId=20625101&action=accept","Decline":"\/events\/index.php\/user\/connection?userId=20625101&action=decline"}]]]

我猜这与[]s 的数量有关,但 JSON 是由 PHP 使用 json_encode() 编码的

任何帮助,将不胜感激!

谢谢 :)

4

2 回答 2

2

您的 PHP 响应实际上应该是:

{
    "notifications": [
       ["test would like to connect with you",
        {
           "Accept":"\/events\/index.php\/user\/connection?userId=20625101&action=accept",
           "Decline":"\/events\/index.php\/user\/connection?userId=20625101&action=decline"
        }
       ]
    ]
}

请注意,上面的,notification是字符串表示的对象内部的一个字段。这将允许您以使用$.each(..).


您正在做的方式是拥有一个数组(注意响应中的初始[和最后一个)。]错误是因为$.each调用data.notification.lengthwhere .lengthis an operation on undefined。


PHP 端代码应该如下所示:

echo json_encode(array("notifications" => $notifications));

而不是(我的猜测):

echo json_encode(array("notification", $notifications));
于 2012-07-02T18:08:12.233 回答
2

你所拥有的是一个 JSON 数组。我猜你正在寻找这样的东西:

{
    "notifications": [
        ["test would like to connect with you",
        {
            "Accept": "\/events\/index.php\/user\/connection?userId=20625101&action=accept",
            "Decline": "\/events\/index.php\/user\/connection?userId=20625101&action=decline"
        }]
    ]
}

虽然我认为更好的结构是:

{
    "notifications": [
        {
            "message": "test would like to connect with you",
            "Accept": "\/events\/index.php\/user\/connection?userId=20625101&action=accept",
            "Decline": "\/events\/index.php\/user\/connection?userId=20625101&action=decline"
        }
    ]
}

这种方式notification成为对象的属性,这意味着您可以通过data.notifications. 否则,您必须通过data[1](data[0]将包含基本上变得毫无意义的字符串“通知”) 访问通知。

以下示例应该让您了解如何在 PHP 中设置数据:

<?php
  $array = array(
      "notifications" => array(
          array(
              "message" => "Test would like to connect with you",
              "Accept" => "/events/index.php/user/connection?userId=20625101&action=accept",
              "Decline" => "/events/index.php/user/connection?userId=20625101&action=decline"
          )
      )
  );

  echo json_encode($array);
?>
于 2012-07-02T18:09:28.767 回答