2014-11-04 92 views
0

我想要一個javascript.datatable(http://www.datatables.net/)顯示我已經作爲json字符串通過的數據集。用json填充javascript.datatables?

$(document).ready(function() { 
    $('#Reports').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="ReportsTable"></table>'); 
    var data = <%=jsonResult%>; 
    $('#ReportsTable').dataTable({ 
    "data": data, 
    "columns": [ 
     { "title": "id" }, 
     { "title": "name" }, 
     { "title": "regAndId" }, 
     { "title": "type" }, 
     { "title": "timeStamp" } 
    ] 
    }); 
}); 

我jsonResult或數據變量如下所示:

{ 
    "reports": [ 
     { 
      "id": "421b4b9b-63d5-4fe2-a929-a85d9fe9d2ef", 
      "name": "TAMANYA PROPERTIES", 
      "regAndId": "1989/011313/23", 
      "timeStamp": "2014/10/31 01:57:51 PM", 
      "type": "Company" 
     }, 
     { 
      "id": "56751c5d-84b2-463a-95be-9feb2fa02c10", 
      "name": "TESTA PROPERTY COMPANY PTY", 
      "regAndId": "1980/004250/07", 
      "timeStamp": "2014/10/31 10:29:09 AM", 
      "type": "Company" 
     } 
    ] 
} 

我得到的錯誤是:

Uncaught TypeError: undefined is not a function

+0

看起來你沒有正確包括'datatables'插件。關於哪個功能在抱怨? – dreyescat 2014-11-04 09:46:29

+0

可能的重複:http://stackoverflow.com/questions/23295424/uncaught-typeerror-undefined-is-not-a-function-for-datatables – vatsal 2014-11-04 09:52:06

回答

1

如果DataTable庫未正確加載,可能會發生這種情況。首先應該加載jQuery,然後加載dataTables。

0

嘗試改變這種

var data = <%=jsonResult%>; 

var data = '<%=jsonResult%>'; 

請注意引號。 這是需要的,因爲你正在分配的內容需要json字符串,而不僅僅是一個對象/函數。

1

假設您已正確包含jQuery和DataTables庫,則需要根據您的數據結構配置columns。像這樣的東西應該爲你工作:

$(document).ready(function() { 
    $('#Reports').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="ReportsTable"></table>'); 
    var data = { 
    "reports": [ 
     { 
      "id": "421b4b9b-63d5-4fe2-a929-a85d9fe9d2ef", 
      "name": "TAMANYA PROPERTIES", 
      "regAndId": "1989/011313/23", 
      "timeStamp": "2014/10/31 01:57:51 PM", 
      "type": "Company" 
     }, 
     { 
      "id": "56751c5d-84b2-463a-95be-9feb2fa02c10", 
      "name": "TESTA PROPERTY COMPANY PTY", 
      "regAndId": "1980/004250/07", 
      "timeStamp": "2014/10/31 10:29:09 AM", 
      "type": "Company" 
     } 
    ] 
    }; 
    $('#ReportsTable').dataTable({ 
    "data": data.reports, 
    "columns": [ 
     { "data": "id" }, 
     { "data": "name" }, 
     { "data": "regAndId" }, 
     { "data": "type" }, 
     { "data": "timeStamp" } 
    ] 
    }); 
}); 

demo