简体   繁体   中英

Display data returned with Ajax in table format

I am using Ajax+Jquery to get data from a PHP api. In that PHP api at the last step I do-

$data_enc = json_encode($data); echo $data_enc;

And I get this returned-

{"headers":["Age","Count","Consent","Intent"],"data":{"17":{"Age":"17","Count":2,"Consent":"2","Intent":0},"18":{"Age":"108","Count":3,"Consent":"3","Intent":0},"115":{"Age":"115","Count":1,"Consent":"1","Intent":0},"117":{"Age":"117","Count":2,"Consent":"2","Intent":0},"118":{"Age":"118","Count":1,"Consent":"1","Intent":0},"Totals":{"Age":"Total","Count":67,"Consent":67,"Intent":0}}}

On the Jquery side,

success: function(data){
    alert(typeof(data)); //returns string
},

When I do a typeof(data) in the jQuery Ajax success, it says that its a string. I need to display this data in a table with columns as Age, Count, Consent, Intent.

I tried looping over the object on the jQuery side but couldn't get the desired result.

Use dataType: 'json' in your ajax request.

To build the table:

HTML:

<table id="myTable">
   <thead></thead>
   <tbody></tbody>
</table>

JS:

$.ajax({
   url: '...',
   dataType: 'json',
   success: function (result) {
       $('#myTable tr').empty();
       var header = $('#myTable thead');
       var body = $('#myTable tbody');
       var hTr;
       $('#myTable thead').append(hTr = $('<tr>'));
       // Headers
       for (var h = 0; h < result.headers.length; h++) {
          hTr.append($('<th>', { text: result.headers[h] }))
       }
       // Body
       for (var d in result.data) {
          var data = result.data[d];
          $('#myTable tbody').append($('<tr>')
              .append($('<td>', { text: data.Age }))
              .append($('<td>', { text: data.Count }))
              .append($('<td>', { text: data.Consent }))
              .append($('<td>', { text: data.Intent }))
          )
       }
   }
})

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