使用Ajax在HTML表中显示嵌套的json

时间:2018-06-26 11:57:27

标签: javascript jquery json ajax

我有以下json数据作为示例。但是,我无法将其显示在html表中。但是,它仅返回3列,显示“未定义”。如何正确访问我的json数据?

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

我已经尝试过将其显示在html表中:

$(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);
    });
});

1 个答案:

答案 0 :(得分:2)

尝试一下:

    $(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);
    }); 
});