DataTables Multiple Tables from Multiple JSON Arrays

筅森魡賤 提交于 2019-12-25 08:27:31

问题


I want to output two tables, each sourcing information from two separate arrays within the same JSON source, but for some reason my code doesn't work.

JSON Message:

{
  "Policies": [
    {
      "name": "A",
      "id": "1",
      "score": "0"
    }
  ],
  "Services": [
    {
      "name": "B",
      "id": "2",
      "score": "0"
    }
  ]
}

HTML Code:

<table id="policies-table" class="display" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>ID</th>
      <th>Score</th>
    </tr>
  </thead>
</table>
<table id="services-table" class="display" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>ID</th>
      <th>Score</th>
    </tr>
  </thead>
</table>

JavaScript Code:

var the_url = "www.example.com"

var columnsDef = [
    { data : "name" },
    { data : "id" },
    { data : "score" }
];

$(document).ready(function() {
    $('#policies-table').DataTable({
        ajax : {
        url : the_url,
        dataSrc: "Policies"
                },
        columns : columnsDef
}),

    $('#services-table').DataTable({
        ajax : {
        url : the_url,
        dataSrc: "Services"
                },
        columns : columnsDef
})
});

回答1:


You are not iterating through your JSON variable. As prabodhprakash suggested, writing "Policies" and "Services" won't help either.

I suggest you to take a look at this fiddle

You can initialize multiple datatables with the same syntax that you use for initializing a single one:

var json = {
  "Policies": [{
    "name": "A",
    "id": "1",
    "score": "0"
  }],
  "Services": [{
    "name": "B",
    "id": "2",
    "score": "0"
  }]
}


var policyTable = $("#policies-table").DataTable({
  "data" : (json.Policies),
  "columns": [
        { "data": "name" },
        { "data": "id" },
        { "data": "score" }]
});

var serviceTable = $("#services-table").DataTable({
    "data" :(json.Services),
    "columns": [
        { "data": "name" },
        { "data": "id" },
        { "data": "score" }]
});


来源:https://stackoverflow.com/questions/41280486/datatables-multiple-tables-from-multiple-json-arrays

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