DataTable with JSON data

痞子三分冷 提交于 2019-12-10 18:23:24

问题


I am trying to create a table using DataTable but having a hard time getting DataTable to load with JSON object.

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();
}

Requesting the JSON file via a XMLHttpRequest() request.

short sample of the JSON object:

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

Currently only trying to show the meta part in a DataTable table:

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

index.html part:

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

Only getting a No data available in table when running, and I am obviously missing something.


回答1:


The "data" attribute for initializing your Data Table is expecting a list (Each element representing a row). Modify your ajax response, so each row is an element in the jsonData list. I also added quotes around all the JSON options.

var jsonData = [
    { "meta": { "version": 1, "type": "test" } }
];

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

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

Since you want to load your data via ajax, you should look at the ajax options built in to the DataTables API. https://datatables.net/manual/ajax



来源:https://stackoverflow.com/questions/51023879/datatable-with-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!