目前是第一次使用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 是由 PHP 使用 json_encode() 编码
任何帮助将不胜感激!
谢谢:)
你有一个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);
?>
你的 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));