简体   繁体   中英

Json encode data looping in js

I have data that php returned to JS but i dunno how to loop it to access the information... i have this:

    result = call_data('get_chat.php');
            console.log(result);
    for(var data in result){

        alert(result[data]["id"]); //says undefined

    }

Console Log shows:

   [{"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"}]  

So i want to loop each data from it but how do i do it im really confused!! It just says undefined each time.

If typeof result === "string" , then you still need to parse the response before you can iterate over it:

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

Then, as others have pointed out, you should use a simple for loop with Array s:

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

for..in loops will iterate all enumerable keys rather than just indexes.

It looks like your php code returns an array of objects, so you need to first iterate through the array, and then access the id key like so:

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  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM