2017-08-28 100 views
1

顯示JSON數據我從我的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()將數據放入其中。

有沒有人有更優雅/高效的建議?

回答

0

在這裏,你去了一個解決方案https://jsfiddle.net/qpu3cn5u/

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>'); 
 
    } 
 
}
th, td { 
 
    border: 1px dashed #000; 
 
    padding: 5px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <thead> 
 
    <tr></tr> 
 
    </thead> 
 
    <tbody></tbody> 
 
</table>

只有你需要檢查與客戶名稱件事馬上就要結束了。

希望這會幫助你。

+0

JavaScript運行時錯誤:Object.keys:參數不是Object ...這是IE 11的問題? – Philo