2016-05-18 51 views
0

HTML:如何遍歷對象的陣列中的數據表2.1

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/t/bs-3.3.6/jq-2.2.0,dt-1.10.11/datatables.min.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/t/bs-3.3.6/jq-2.2.0,dt-1.10.11/datatables.min.js"></script> <table id="dTExample" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Account #</th> <th>Customer #</th> <th>Customer Name</th> <th>Location</th> <th>Address</th> <th>Product</th> </tr> </thead> </table>

JS:

function populateData(table) { var aTable; aTable = $(table).dataTable({ sAjaxSource: 'SamplePage.aspx', fnServerData: function (sSource, aoData, fnCallback) { JsonLoader("SamplePage.aspx/GetServiceLookupList", "{'idType': 'an', 'idValue': '123'}", fnCallback); }, columns: [ { data: "billAccountNumber" }, { data: "customerNumber" }, { data: "customerName" }, { data: "serviceLocationName" }, { data: "serviceLocationAddress" }, { data: "serviceComponentProductName" } ] }); }

function JsonLoader(url, data, fnCallback) { $.ajax({ type: "POST", url: url, contentType: "application/json; charset=utf-8", dataType: "json", data: data, success: function (result) { var objAjax = JSON.parse(result.d); fnCallback(objAjax); }, error: function (err, ajaxOptions, thrownError) { //Error } }); }

返回JSON:

{ 「iTotalRecords」:100, 「iTotalDisplayRecords」:100, 「aaData」:[ { 「billAccountName」: 「FAKE CORP」, 「customerNumber之」: 「123」, 「客戶名稱」: 「假」, 「serviceLocationName」: 「假公司」, 「serviceLocationAddress」: 「PO BOX 123丹佛CO」, 「serviceComponentProductName」: 「產品X」 }, { 「billAccountName」: 「REAL CORP」, 「customerNumber之「:」456「, 」customerName「:」Real「, 」serviceLocationName「:」Real Corp「, 」serviceLocationAddress「:」PO BOX 456 Ft Collins CO「, 「serviceComponentProductName」: 「產品Z」 },[...]}

所以basiclly aaData是100個對象,其每一個有一個 「billAccountName」 的陣列。當我運行我的代碼時,表格上的記錄數量正確顯示,但表格爲空。不知道如何去迭代所有這些對象並將它們各自的字段名映射到表中。請幫忙。

回答

1

返回的JSON有「iTotalRecords」:100,「iTotalDisplayRecords」:100,這實際上是造成問題的原因。你的Json應該有一個對象數組,其中有一個值可以輸入到數據表中。您可以創建一個新數組並存儲[「aaData」:[{「billAccountName」:「FAKE CORP」,「customerNumber」:「123」,「customerName」:「Fake」,「serviceLocationName」:「Fake Corp」, 「serviceLocationAddress」:「PO BOX 123 Denver CO」,「serviceComponentProductName」:「Product X」},{「billAccountName」:「REAL CORP」,「customerNumber」:「456」,「customerName」:「Real」,「serviceLocationName 「:」Real Corp「,」serviceLocationAddress「:」PO BOX 456 Ft Collins CO「,」serviceComponentProductName「:」Product Z「},{...},]]或者返回的JSON應該是這樣的格式):

{「aaData」:[{「billAccountName」:「FAKE CORP」,「customerNumber」:「123」,「customerName」:「假」,「serviceLocationName」:「假公司」,「serviceLocationAddress 「:」PO BOX 123 Denver CO「,」serviceComponentProductName「:」Product X「},{」billAccountName「:」REAL CORP「,」customerNumber「:」456「,」customerName「:」Real「 ,「serviceLocationName」:「Real Corp」,「serviceLocationAddress」:「PO BOX 456 Ft Collins CO」,「serviceComponentProductName」:「Product Z」}]}

+0

謝謝,這有幫助! – ahetman