2012-07-02 63 views
0

目前第一次使用JSON工作並且幾乎沒有jQuery的經驗。 我有這個功能大幹快上$阿賈克斯要求的「成功」觸發:jQuery JSON解析 - 「對象未定義」

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是由PHP使用json_encode編碼()

任何幫助,將不勝感激!

謝謝:)

回答

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[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響應實際上應該是:

{ 
    "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)); 
+0

謝謝!你知道爲什麼我的json_encode($ array)返回一個JSON數組而不是對象嗎? –

+0

你可以把PHP代碼嗎? – SuperSaiyan

+0

感謝您的幫助!我想出了它爲什麼給JSON數組 - 因爲我沒有在數組中提供name =>值對。用於C和Java陣列:) –