为什么我的JSON对象未定义? [英] Why is my JSON object undefined?
本文介绍了为什么我的JSON对象未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试解析JSON数据结构,但我认为应该返回的数据未定义.
I'm trying to parse a JSON data structure but what I think should be data is returning undefined.
这是我正在使用的jQuery:
Here is the jQuery I'm using:
....
var messages = data.messages;
$.each(messages, function(i, val) {
var user = messages[i];
//console.log(user);
console.log(user['msg']);
});
PHP数据结构如下:
The PHP data structure look like this:
...
$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);
如果我将用户转储到控制台,则输出如下所示:Object
If I dump user to the console the output look like this:Object
{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"
...
有人知道为什么我无法访问和检索味精的内容吗?
Any idea why I can't access and retrieve the contents of msg?
推荐答案
重写PHP,以避免在$row['username']
内嵌套msg
:
Rewrite your PHP to avoid nesting msg
inside of $row['username']
:
$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应该可以按原样工作.
With that change, your JavaScript should work as-is.
这篇关于为什么我的JSON对象未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文