DataTables Multiple Tables from Multiple JSON Arra

2019-09-08 11:48发布

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条回答
来,给爷笑一个
2楼-- · 2019-09-08 12:30

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" }]
});
查看更多
登录 后发表回答