使用json填充javascript.datatables?

时间:2014-11-04 08:59:42

标签: javascript jquery json datatable

我正在尝试使用javascript.datatable(http://www.datatables.net/)显示我作为json字符串传递的数据集。

$(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"
        }
    ]
}

我得到的错误是:

  

未捕获的TypeError:undefined不是函数

3 个答案:

答案 0 :(得分:1)

如果未正确加载DataTable库,可能会发生这种情况。首先应加载jQuery,然后加载dataTables。

答案 1 :(得分: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

答案 2 :(得分:0)

尝试更改此

 var data = <%=jsonResult%>;

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

注意引号。 这是必需的,因为您要分配的内容是期望json字符串而不仅仅是对象/函数。