Json在js中对数据循环进行编码

Json encode data looping in js

本文关键字:循环 编码 数据 js Json      更新时间:2023-09-26

我有php返回给JS的数据,但我不知道如何循环它来访问信息。。。我有这个:

    result = call_data('get_chat.php');
            console.log(result);
    for(var data in result){
        alert(result[data]["id"]); //says undefined
    }

控制台日志显示:

   [{"eventtime":"0000-00-00 00:00:00","message":"test2","bywho":"dave","id":"2"},
    {"eventtime":"0000-00-00 00:00:00","message":"testttt","bywho":"dave","id":"1"}]  

所以我想从中循环每个数据,但我怎么做真的很困惑!!它只是每次都说未定义。

如果是typeof result === "string",那么在迭代之前仍然需要解析响应:

result = JSON.parse(call_data('get_chat.php'));

然后,正如其他人所指出的,您应该使用一个带有Array的简单for循环:

for (var i = 0, l = result.length; i < l; i++) {
    console.log(result[i]["id"]);
}

for..in循环将迭代所有可枚举键,而不仅仅是索引。

看起来您的php代码返回了一个对象数组,因此您需要首先遍历该数组,然后访问id密钥,如下所示:

for (var i = 0; i < result.length; i++){
  var obj = result[i];
  console.log(obj.id); // this will be the id that you want
  console.log(obj["id"]); // this will also be the id  
}