首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从json对象动态构造有序的html表。

从json对象动态构造有序的html表。
EN

Stack Overflow用户
提问于 2018-06-02 03:55:06
回答 1查看 35关注 0票数 0

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

代码语言:javascript
运行
复制
{
    "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();
     });
    });

我得到了一张这样的桌子:

代码语言:javascript
运行
复制
id   category
1    fruit      2     diary

instead of 

id   category
1    fruit      
2    diary
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50650233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档