简体   繁体   中英

ajax: extract json object from array of json

JSON (inside array from api):

[{"id":"001", "name":"john", "age":"40"}, {"id":"002", "name":"jane", "age":"30"}]

Ajax:

  $.ajax({                                      
  url: 'interface_API.php',                                                              
  dataType: 'json',                    
  success: function(data)         
  {
    for(var i in data){
        var row = data[i];

        var id = row[0];            
        var name = row[1];
        var age = row[2];

    $('#output').append("<tr width='50%'><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td></tr>"); 
    }
  } 
});

The API uses this to construct:

if(mysqli_num_rows($output)){
     while($row = mysqli_fetch_assoc($output)){
         $json[] = $row;
     }
}

However my Output is 'undefined' repeated for each .append

How do i extract each json object from the array & append to the page?

change this:

var id = row[0];            
var name = row[1];
var age = row[2];

to this:

var id = row['id'];            
var name = row['name'];
var age = row['age'];

or this:

var id = row.id;
var name = row.name;
var age = row.age;

Because you already looped in here:

for(var i in data){
    var row = data[i]; // <----here

so you just required to reference it with keys in the js object.

You can change the for loop like this:

$.ajax({                                      
  url: 'interface_API.php',                                                              
  dataType: 'json',                    
  success: function(data)         
  {
    for(var i in data){
        var row = data[i];

        var id = row.id;            
        var name = row.name;
        var age = row.age;

$('#output').append("<tr width='50%'><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td></tr>"); 
}
} 
});

please use the key to identify the json Object while retrieving

var list=[
        {"id":"1","text":"test1"},
        {"id":"2","text":"test2"},
        {"id":"3","text":"test3"},
        {"id":"4","text":"test4"}

         ]


    alert(list[2].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