HTML:
<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”, “customerName”:“假”, “serviceLocationName”:“假公司”, “serviceLocationAddress”:“PO BOX 123 Denver CO”, “serviceComponentProductName”:“Product X” }, { “billAccountName”:“REAL CORP”, “customerNumber”:“456”, “customerName”:“真实”, “serviceLocationName”:“Real Corp”, “serviceLocationAddress”:“PO BOX 456 Ft Collins CO”, “serviceComponentProductName”:“产品Z” },[...]}
所以基本上aaData是一个包含100个对象的数组,每个对象都有一个“billAccountName”。当我运行我的代码时,表上的记录数正确显示,但表是空的。不知道如何迭代所有这些对象并将它们各自的字段名称映射到表中。请帮忙。
答案 0 :(得分:1)
返回的JSON有“iTotalRecords”:100,“iTotalDisplayRecords”:100,实际上导致了问题。您的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“},{...},]]或返回的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”}}}