DataTables来自多个JSON数组的多个表 [英] DataTables Multiple Tables from Multiple JSON Arrays

查看:235
本文介绍了DataTables来自多个JSON数组的多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输出两个表,每个表都从同一JSON源中的两个单独的数组中获取信息,但是由于某些原因,我的代码无法正常工作.

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消息:

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

HTML代码:

<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代码:

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

推荐答案

您没有遍历JSON变量.正如prabodhprakash所建议的那样,编写策略"和服务"也无济于事.

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

我建议您看一下小提琴

您可以使用用于初始化单个数据表的相同语法来初始化多个数据表:

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" }]
});

这篇关于DataTables来自多个JSON数组的多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆