如何在jQuery中解析JSON数组?

use*_*410 5 arrays each jquery json

编辑我检查了jQuery文档,并使用$ .ajax指定的json数据类型返回一个评估的javascript对象,所以eval()不是这里的答案.无论如何,我知道,因为我能够解析单个JSON对象,而不是数组.问题是$ .each-ing my through through through :)

我已经遵循了将jQuery中的JSON数组解析为字母的语法,但由于某种原因它不起作用.我使用$ .ajax获取数组,指定了正确的数据类型,并且在Firebug中可以看到我的PHP脚本的响应是[].然而,当我尝试使用$ .each迭代数组时,当我尝试console.log数组的各个部分时,我得到的都是未定义的值.这是我的PHP脚本制作和编码数组的地方:

if(mysqli_num_rows($new_res) > 0) {
$messages = array();

while($message_data = mysqli_fetch_assoc($query_res)) {
  $message = array(
    'poster' => $message_data['poster'],
    'message' => $message_data['message'],
    'time' => $message_data['time']
  );

  $messages[] = $message;
}

echo json_encode($messages);
} else if(mysqli_num_rows($new_res) == 0) {
$message = array(
  'poster' => '',
  'message' => 'No messages!',
  'time' => 1
);

echo json_encode($message);
}
Run Code Online (Sandbox Code Playgroud)

这是我试图解析它:

   var logged_in = '<?php echo $logged_in; ?>';
   var poster = '<?php echo $_SESSION["poster"];?>';
     $.ajax({
     url: 'do_chat.php5',
     type: 'post',
     data: ({'poster':poster,'logged_in':logged_in}),
     dataType: 'json',
     success: function(data) {
         $.each(data, function(messageIndex, message) {
                    console.log(parseInt($('#chatWindow :last-child > span').html())+' '+message['time']);
       if((parseInt(message['time']) > parseInt($('#chatWindow :last-child > span').html()))) {
     $('#chatWindow').append('<div class="poster">'+message['poster']+'</div><div class="message"><span>'+message['time']+'</span>'+message['message']+'</div>');
       }
       });
     }
     });
Run Code Online (Sandbox Code Playgroud)

如果没有$ .each函数,我可以成功解析单个JSON对象,但不能解析数组.这是我第一次使用JSON和$ .each,我是jQuery的新手,所以如果我的代码有丑陋的话,那就轻松吧!

Ces*_*sar 13

不,eval不安全,你可以使用更安全的JSON解析器:var myObject = JSON.parse(data); 为此使用lib https://github.com/douglascrockford/JSON-js


小智 5

我知道你的帖子发布后很长一段时间了,但我想发帖给其他可能遇到过这个问题的人,并且像我一样偶然发现这篇文章.

似乎有一些关于jquery的东西$.each会改变数组中元素的性质.

我想做以下事情:

$.getJSON('/ajax/get_messages.php', function(data) {

    /* data: 

    [{"title":"Failure","details":"Unsuccessful. Please try again.","type":"error"},
    {"title":"Information Message","details":"A basic informational message - Please be aware","type":"info"}]

    */

    console.log ("Data0Title: " + data[0].title);
    // prints "Data0Title: Failure"

    console.log ("Data0Type: " + data[0].type);
    // prints "Data0Type: error"

    console.log ("Data0Details: " + data[0].details);
    // prints "Data0Details: Unsuccessful. Please try again"


    /* Loop through data array and print messages to console */

});
Run Code Online (Sandbox Code Playgroud)

为了完成循环,我首先尝试使用jquery $.each循环遍历数据数组.但是,正如OP所说,这不起作用:

$.each(data, function(nextMsg) {    
    console.log (nextMsg.title + " (" + nextMsg.type + "): " + nextMsg.details);
    // prints 
    // "undefined (undefined): undefined
    // "undefined (undefined): undefined
});
Run Code Online (Sandbox Code Playgroud)

这并不是很有意义,因为我可以data[0]在数据数组上使用数字键时访问元素.因此,由于使用了数字索引,我尝试(成功)用$.eachfor循环替换块:

var i=0;
for (i=0;i<data.length;i++){
    console.log (data[i].title + " (" + data[i].type + "): " + data[i].details);
    // prints
    // "Failure (error): Unsuccessful. Please try again"
    // "Information Message (info): A basic informational message - Please be aware"
}
Run Code Online (Sandbox Code Playgroud)

所以我不知道潜在的问题,一个基本的,老式的javascript for循环似乎是jquery的功能替代 $.each


med*_*iev 0

你是在那个时间点data的一串,你可以像这样:'[{}]'eval

function(data) {
    data = eval( '(' + data + ')' )
}
Run Code Online (Sandbox Code Playgroud)

然而这种方法远非安全,这会需要更多的工作,但最佳实践是使用 Crockford 的 JSON 解析器来解析它: https: //github.com/douglascrockford/JSON-js

另一种方法是$.getJSON,您需要将dataTypejson 设置为纯 jQuery 依赖方法。