为什么我的JSON对象未定义?

我正在尝试解析JSON数据结构,但我认为应该是数据返回undefined。

这是我正在使用的jQuery:

.... var messages = data.messages; $.each(messages, function(i, val) { var user = messages[i]; //console.log(user); console.log(user['msg']); }); 

PHP数据结构如下所示:

 ... $message_info = array(); $message_info[$row['username']]['prvt'] = 1; $message_info[$row['username']]['msg'] = stripslashes($row['message']); $message_info[$row['username']]['ts'] = $row['timestamp']; ... $message_list[] = $message_info; ... $res->messages = $message_list; echo json_encode($res); 

如果我将用户转储到控制台,输出看起来像这样:对象

 {john: Object} john: Object msg: "test msg" prvt: 0 ts: "2012-12-10 09:16:13" 

这是控制台中的数据:

 Object {success: true, lastid: "60", messages: Array[15]} lastid: "60" messages: Array[15] 0: Object john: Object msg: "test msg" prvt: 0 ts: "2012-12-10 09:16:13" 1: Object john2: Object msg: "test msg2" prvt: 1 ts: "2012-12-10 09:18:13" ... 

知道为什么我无法访问和检索msg的内容吗?

重写你的PHP以避免在$row['username']嵌入msg

 $message_info = array(); $message_info['username'] = $row['username']; // find this in JS with user['username'] $message_info['prvt'] = 1; $message_info['msg'] = stripslashes($row['message']); $message_info['ts'] = $row['timestamp']; 

通过这种更改,您的JavaScript应该按原样运行。

您的用户对象包含由“john”,“john2”等键引用的对象。

 user.john.msg or user.john2.msg 

应该管用。

因此,要在php中构建更通用的json结构,我将执行以下操作:

 ... $message_info['user']['name'] = $row['username']; $message_info['user']['prvt'] = 1; ...