创建表以使用动态列显示json数据

时间:2017-08-28 16:32:14

标签: jquery .net json html-table

我从WebMethod接收Json格式的数据: -

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "Customer_History.aspx/GetData",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                var returnedstring = data.d;

               }
        })
    });
</script>

数据为: - [客户名称,年份:Money_Spent]。对于每年(2000,2001 ...... 2017),客户已经花了一些钱在网上购物代理商。

实施例: - [{"Customer Name":"XXXX","1999":76.000,"2000":68.000,"2001":49.000,"2002":41.000,"2003":47.000,"2004":56.000,"2005":33.000,"2006":51.000,"2007":56.000,"2008":52.000,"2009":55.000,"2010":52.000,"2011":57.000,"2012":55.000,"2013":93.000,"2014":92.000,"2015":62.000,"2016":71.833},{"Customer Name: "YYYY",......... etc etc

现在因为多年来的列是动态的。我想我必须解析数据,找到最小年份值和最大年份值,然后根据它创建一个表结构,如下所示: -

Customer | 1999 | 2000 | 2001 ----->
--------------------------------
 XXXX    | $$   | $$   | $$ --------->
--------------------------------
 YYYY    | $$   | $$   | $$ --------->
--------------------------------

我也在考虑定义列名后,使用jquery datables()将数据放入其中。

有没有人有更优雅/有效的建议?

1 个答案:

答案 0 :(得分:1)

您可以使用解决方案https://jsfiddle.net/qpu3cn5u/

&#13;
&#13;
var data = [{"Customer Name":"XXXX","1999":76.000,"2000":68.000,"2001":49.000,"2002":41.000,"2003":47.000,"2004":56.000,"2005":33.000,"2006":51.000,"2007":56.000,"2008":52.000,"2009":55.000,"2010":52.000,"2011":57.000,"2012":55.000,"2013":93.000,"2014":92.000,"2015":62.000,"2016":71.833},{"Customer Name": "YYYY","1999":76.000,"2000":68.000,"2001":49.000,"2002":41.000,"2003":47.000,"2004":56.000,"2005":33.000,"2006":51.000,"2007":56.000,"2008":52.000,"2009":55.000,"2010":52.000,"2011":57.000,"2012":55.000,"2013":93.000,"2014":92.000,"2015":62.000,"2016":71.833}];

var colHeader = Object.keys(data[0]);

for(var i=0; i<colHeader.length; i++) {
  $('table thead tr').append('<th>' + colHeader[i] + '</th>');
}

for(var i=0; i<data.length; i++){
  $('table tbody').append('<tr></tr>')
  for(var j= 0; j<colHeader.length; j++){
    $('table tbody tr').last().append('<td>' + data[i][colHeader[j]] + '</td>');
  }
}
&#13;
th, td {
  border: 1px dashed #000;
  padding: 5px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr></tr>
  </thead>
  <tbody></tbody>
</table>
&#13;
&#13;
&#13;

只有您需要检查客户名称才会结束。

希望这会对你有所帮助。

相关问题