2012-07-02 62 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阵列:) –