0

I'm trying to parse a JSON data structure but what I think should be data is returning undefined.

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']);

});

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);

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"

This is what data looks like in the console:

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?

4

2 回答 2

1

重写你的 PHP 以避免嵌套msg$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 应该可以按原样工作。

于 2012-12-10T20:55:18.937 回答
0

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

user.john.msg or user.john2.msg

应该管用。

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

...
$message_info['user']['name'] = $row['username'];
$message_info['user']['prvt'] = 1;
...
于 2012-12-10T20:53:06.307 回答