Javascript 从json对象动态构造有序html表

Javascript 从json对象动态构造有序html表,javascript,jquery,html,Javascript,Jquery,Html,ajax响应返回json对象,我想从中构造一个表。json包含数组中的列标题和另一个字典数组中的实际数据。我希望表列按照标题数组排序: { "columns": ["id", "category"], "data":[ {"category": "fruit","id": 1}, {"category": "diary","id": 2} ] } $(document).ready(function() { $("#submit"

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

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

      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>"
html+=“”
每个(response.data,函数(索引,值){
html+=“”;//新代码
每个(response.columns,函数(idx,col){
html+=“”+值[col]+“”
})
html+=“”;//新代码
})
html+=“”

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

      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>"
html+=“”
每个(response.data,函数(索引,值){
html+=“”;//新代码
每个(response.columns,函数(idx,col){
html+=“”+值[col]+“”
})
html+=“”;//新代码
})
html+=“”