2012-07-02 7 views
0

현재 jQuery를 거의 사용하지 않고 JSON을 처음 사용하고 있습니다.jQuery JSON 구문 분석 - "개체가 정의되지 않았습니다."

내가 불을 지르고 콘솔 진술에 오류가 발생하지만
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"}]]] 

나는 그것이 []들 수 있지만, JSON이로 json_encode를 사용하여 PHP로 인코딩 된 함께 할 수있는 뭔가가 추측()

는 어떤 도움을 주시면 감사하겠습니다!

감사합니다 :)

답변

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" 
     }] 
    ] 
} 

더 나은 구조는 다음과 같습니다 : 나는 당신이 이런 식으로 뭔가를 찾고 있었다 같은데요

이 방법 notification가 액세스 할 수있는 의미 객체의 속성을하게

{ 
    "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" 
     } 
    ] 
} 
그것을 통해 data.notifications. 그렇지 않으면 을 통해 알림에 액세스해야합니다 ( 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); 
?> 
+0

환상적! 당신의 도움을 주셔서 감사합니다 :) –

2

귀하의 PHP 응답이 실제로해야한다 : 위의와, notification 문자열이 나타내는 객체의 내부 필드입니다

{ 
    "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" 
     } 
     ] 
    ] 
} 

참고. $.each(..)을 사용하면 반복 할 수 있습니다.


당신이하고있는 방법은 배열 (초기 [ 및 응답의 마지막 ]주의)를함으로써 그 것이다. 오류는 $.eachdata.notification.length을 호출하기 때문에 발생합니다. 여기서 .length은 정의되지 않은 작업입니다. 측 코드가 다소 아래와 같이해야


PHP :

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

대신에 (내 생각) :

echo json_encode(array("notification", $notifications)); 
+0

당신을 감사합니다! 내 json_encode ($ array)가 객체가 아닌 JSON 배열을 반환하는 이유를 알고 있습니까? –

+0

PHP 코드도 넣을 수 있습니까? 도움을 주신 덕분에 – SuperSaiyan

+0

! 왜 배열에 이름 => 값 쌍을 제공하지 않았기 때문에 JSON 배열을 제공하는지 알아 냈습니다. C 및 Java 배열에 사용 :) –