【问题标题】:DataTable with JSON data带有 JSON 数据的 DataTable
【发布时间】:2018-12-04 01:16:31
【问题描述】:

我正在尝试使用 DataTable 创建一个表,但很难让 DataTable 加载 JSON 对象。

function getData() {
var request = new XMLHttpRequest();
var json = "link-to-my-json-object";
// Get JSON file
request.onload = function() {
  if ( request.readyState === 4 && request.status === 200 ) {
    var JSONObject = JSON.parse(request.responseText);
    createTable(JSONObject);
  } else if(request.status == 400) { console.log("Error", request.status);}
};
request.open("GET", json, true);
request.send();
}

通过 XMLHttpRequest() 请求请求 JSON 文件。

JSON 对象的简短示例:

{
"meta": {
"version": 1,
"type": "test"
},
"reports": [
{
  "report-metadata": {
    "timestamp": 1528235303.721987,
    "from-ip": "0.0.0.0"
  }, 
//and so on...

目前只尝试在 DataTable 表中显示 meta 部分:

function createTable(jsonData){ 
 $(document).ready(function(){
  $('#table').dataTable({
    data: jsonData,
    columns: [
      { data: 'meta.type' },
      { data: 'meta.version' }
    ]
  });
 });
}

index.html 部分:

<table id="table" class="display" style="width:100%"></table>

运行时只得到一个 No data available in table,我显然遗漏了一些东西。

【问题讨论】:

    标签: javascript jquery json datatables datatables-1.10


    【解决方案1】:

    用于初始化数据表的“数据”属性需要一个列表(每个元素代表一行)。修改您的 ajax 响应,因此每一行都是 jsonData 列表中的一个元素。我还在所有 JSON 选项周围添加了引号。

    var jsonData = [
        { "meta": { "version": 1, "type": "test" } }
    ];
    
    $('#table').DataTable({
        "data": jsonData,
        "columns": [
          { "data": "meta.type" },
          { "data": "meta.version" }
        ]
    });
    

    https://datatables.net/reference/option/data

    由于您想通过 ajax 加载数据,因此您应该查看 DataTables API 中内置的 ajax 选项。 https://datatables.net/manual/ajax

    【讨论】:

      猜你喜欢
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 2020-07-10
      • 2014-11-02
      相关资源
      最近更新 更多