如何访问Dynatable AJAX调用请求的JSON中的其他数据

时间:2017-05-18 09:01:08

标签: javascript jquery json ajax dynatable

我正在使用dynatable.com插件创建存储在我们数据库中的学校表。该表可以过滤,因此并不总是显示学校的总数。我们不会显示“学生人数”栏目,但会尝试在表格底部显示“学生总数”摘要。

页面上的html如下:

<table id="dynatable">
  <thead>
    <tr>
      <th data-dynatable-column="id">ID</th>
      <th data-dynatable-column="schoolName">School Name</th>
      <th data-dynatable-column="contactName">Contact Name</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3"><span id="numPupils"></span> Pupils</td>
    </tr>
  </tfoot>
</table>

随后是JS:

<script>
  $('#dynatable').dynatable({
    dataset: {
      ajax: true,
      ajaxUrl: '/my/json/page.json',
      ajaxOnLoad: true,
      records: []
    }
  });
</script>

检索了一个JSON示例(请注意底部的额外totalNumPupils字段):

{
  "records": [
    {
      "id": "1",
      "schoolName": "ABC School",
      "contactName": "Terry"
    },
    {
      "id": "17",
      "schoolName": "DEF School",
      "contactName": "Claire"
    },
    {
      "id": "45",
      "schoolName": "GHI School",
      "contactName": "Barry"
    }
  ],
  "queryRecordCount": 3,
  "totalRecordCount": 450,
  "totalNumPupils": 794
}

我试图确定是否有办法访问dynatable的ajax调用请求的responseJSON.totalNumPupils,或者我是否必须执行自己的ajax调用,确定学生数量,然后传入JSON到后来的可动态函数?

1 个答案:

答案 0 :(得分:1)

请参阅代码段。您可以使用普通的AJAX来获取JSON有效负载,然后使用来自AJAX响应的数据填充dynatable,同时访问唯一的totalNumPupils属性。

&#13;
&#13;
$('#dynatable').dynatable({
  dataset: {
    ajax: true,
    ajaxUrl: 'https://api.myjson.com/bins/1ezw8l',
    ajaxOnLoad: true,
    records: []
  }
});

$.ajax({
  url: 'https://api.myjson.com/bins/1ezw8l',
  success: function(data) {
    $('#dynatable').dynatable({
      dataset: {
        ajax: false,
        records: data
      }
    });
    $('#numPupils').text("Total Pupils: " + data.totalNumPupils);
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.css" rel="stylesheet" />

<table id="dynatable">
  <thead>
    <tr>
      <th data-dynatable-column="id">ID</th>
      <th data-dynatable-column="schoolName">School Name</th>
      <th data-dynatable-column="contactName">Contact Name</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3"><span id="numPupils"></span> Pupils</td>
    </tr>
  </tfoot>
</table>
&#13;
&#13;
&#13;