0

現在、JSON を初めて使用しており、jQuery の経験はほとんどありません。$.ajax リクエストの「成功」でトリガーされるこの関数があります。

function(data) {

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

}

ただし、firebug コンソールに「オブジェクトは未定義です」「長さ = 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 は json_encode() を使用して PHP によってエンコードされました

どんな助けでも大歓迎です!

ありがとう :)

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.length.length未定義の操作であるためです。


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.notificationsdata[1]それ以外の場合は、 (data[0]本質的に無意味になる文字列「notifications」が含まれます)経由で通知にアクセスする必要があります。

次の例は、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 に答える