首页 > 解决方案 > 从 json 对象动态构造一个有序的 html 表

问题描述

ajax 响应正在返回 json 对象,我想从中构造一个表。json 包含数组中的列标题和另一个字典数组中的实际数据。我希望根据标题数组对表列进行排序:

{
    "columns": ["id", "category"],
    "data":[
      {"category": "fruit","id": 1},
      {"category": "diary","id": 2}
    ]
}



  $(document).ready(function() {
    $("#submit").click(function(event) {
      $.ajax({
        data: {
          user: $('#user').val(),
        },
        type: 'POST',
        dataType: "json",
        url: '/process'
       })
        .done(function(response) {
         if (response.error) {
          alert('Error!');
        }
        else {
          var html = '<table class="table table-bordered"><thead><tr>';
          jQuery.each(response.columns, function(index, value) {
              html += "<th>" + value + "</th>"
          })
          html += "</tr></thead><tbody><tr>"
          jQuery.each(response.data, function(index, value) {
               jQuery.each(response.columns, function(idx, col) {
                    html+="<td>" + value[col] + "</td>"
               })
          })
          html+="</tr></tbody></table>"
          $(resulttable).append(html);
        }
       });
      event.preventDefault();
     });
    });

我得到一张这样的桌子:

id   category
1    fruit      2     diary

instead of 

id   category
1    fruit      
2    diary

标签: javascriptjqueryhtml

解决方案


您需要为每个数据行创建一个新的表格行。

      html += "</tr></thead><tbody>"
      jQuery.each(response.data, function(index, value) {
           html += "<tr>"; //new code
           jQuery.each(response.columns, function(idx, col) {
                html+="<td>" + value[col] + "</td>"
           })
           html += "</tr>"; //new code
      })
      html += "</tbody></table>"

推荐阅读