简体   繁体   中英

Displaying nested json in an HTML table using ajax

I have the following json data as an example below. However, I could not get it to be displayed in an html table.However, it only returns 3 columns which displays "undefined". How do I properly access my json data?

{
  "count": 3,
  "entries": [
    {
      "affiliation": "Establishment1",
      "city": "City1",
      "code": "Code1",
      "contact": "Contact1",
      "firstname": "firstname1",
      "lastname": "lastname1",
      "middleinitial": "middleinitial1"
    },
    {
      "affiliation": "Establishment2",
      "city": "City2",
      "code": "Code2",
      "contact": "Contact2",
      "firstname": "firstname2",
      "lastname": "lastname2",
      "middleinitial": "middleinitial2"
    },
    {
      "affiliation": "Establishment3",
      "city": "City3",
      "code": "Code3",
      "contact": "Contact3",
      "firstname": "firstname3",
      "lastname": "lastname3",
      "middleinitial": "middleinitial3"
    },
  ],
  "status": "ok"
}

I have tried doing this to display it in an html table:

$(document).ready(function () {
    $.getJSON('http://127.0.0.1:5000/counselorss', function (data) {
        var mdata = '';
        $.each(data, function (key, value) {
            mdata += '<tr>';
            mdata += '<td>'+value.lastname + '</td>';
            mdata += '<td>'+value.firstname + '</td>';
            mdata += '<td>'+value.middleinitial + '</td>';
            mdata += '<td>'+value.contact + '</td>';
            mdata += '<td>'+value.affiliation + '</td>';
            mdata += '<td>'+value.city + '</td>';
            mdata += '<td>'+value.code + '</td>';
            mdata += '</tr>';
        });
        $('#counselorstable').append(counselor_data);
    });
});

Try this one:

    $(document).ready(function () {
    $.getJSON('http://127.0.0.1:5000/counselorss', function (data) {
        var mdata = '';
        data = JSON.parse(data);
        $.each(data['entries'], function (key, value) {
            mdata += '<tr>';
            mdata += '<td>'+value.lastname + '</td>';
            mdata += '<td>'+value.firstname + '</td>';
            mdata += '<td>'+value.middleinitial + '</td>';
            mdata += '<td>'+value.contact + '</td>';
            mdata += '<td>'+value.affiliation + '</td>';
            mdata += '<td>'+value.city + '</td>';
            mdata += '<td>'+value.code + '</td>';
            mdata += '</tr>';
        });
        $('#counselorstable').append(counselor_data);
    }); 
});

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