javascript - 如何使用 DataTables、Ajax 调用和 Json 响应重新加载表数据?
问题描述
我有一个通过 Thymeleaf 生成的表。我想使用 jQuery 刷新表格的内容。
<table class="table table-hover" id="main-table">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Network Id</th>
<th class="col-md-2 text-center">Rep date</th>
<th class="col-md-2 text-center">Hashrate [KH/s]</th>
</tr>
</thead>
<tbody>
<tr th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
<td class="text-center" id="hashrateId" th:text="${networkHashrate.id}"> Sample id</td>
<td class="text-center" id="repDate" th:text="${@findAndDisplayDataService.formatDate(networkHashrate.repDate)}">Sample rep-date</td>
<td class="text-center" id="hashrate" th:text="${@findAndDisplayDataService.formatHashrate(networkHashrate.hashrate)}">Sample hashrate</td>
</tr>
</tbody>
</table>
我想出了这样的功能,每 8 秒更新一次表格内容:
$(document).ready(function() {
var table = $('#main-table').DataTable({
ajax: {
url: '/refresh',
dataSrc:''
},
paging: true,
lengthChange: false,
pageLength: 20,
stateSave: true,
info: true,
searching: false,
"aoColumns": [
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "desc", "asc" ] }
],
"order": [[ 0, "asc" ]]
});
setInterval(function(){
table.ajax.reload();
}, 8000);
});
这是 JSON 响应:
[{
"id":1,
"repDate":{
"offset":{ },
"nano":880042000,
"year":2018,
"monthValue":4,
"dayOfMonth":25,
"hour":12,
"minute":58,
"second":53,
"month":"APRIL",
"dayOfWeek":"WEDNESDAY",
"dayOfYear":115
},
"hashrate":5114926.0
},...more entries
]
打印一个空表,我不断收到错误消息:
Uncaught TypeError: Cannot read property 'reload' of undefined
还有一个警报弹出窗口说:
Data Tables warning: table id=main-table - Requestem unknown parameter '0' for row 0 column 0. For more information about this error, please see: http://datatables.net/tn/4
编辑
我将表声明移到函数之外。现在我只是不断收到警告。
编辑 2
我按照你说的做了,数据不断刷新,但问题仍然很少。
首先,我的stateSave: true
财产停止工作,所以当重新加载表格时,它总是回到第一页。
其次,我丢失了我最初在文件中的所有样式(class="text:center"
例如)和属性。on:click
html
解决方案
尝试在 $(document).ready 之前声明表:
var table;
$(document).ready(function() {
table = $('#main-table').DataTable({"serverSide": true, ...})
setInterval(function(){
table.ajax.reload();
}, 8000);
})
该错误与您的列定义有关,请尝试以这种方式定义列:
"columnDefs": [
{
"targets": 0,
"data": "id",
},
{
"targets": 1,
"data": "repDate",
},
{
"targets": 2,
"data": "repDate",
}
]
推荐阅读
- sql - Hasura GraphQL 查询:具有来自相关实体的值的 where 子句
- android - 我想在 Android 和 KOTLIN 中使用 MVVM 实现,请帮助我
- javascript - 将 PDF 上传到 S3 时需要设置哪些标题,因此它不会被下载而是在浏览器中查看或呈现?
- apache-nifi - 如何使 Nifi 处理器事件驱动
- java - Firebase 实时数据库 - 如何使用 java sdk 管理数据库规则
- java - Proguard Maven 插件不使用指定的 Proguard 版本
- javascript - 将事件处理程序仅分配给 DOM 中的 HTML 子集的最佳方式(使用 jQuery)是什么?
- python - 如何在 HANA Python 连接器的 Cursor.Execute 方法中将多个值作为参数传递
- android - 如何在同一活动中编写 Google 和 Facebook 登录?
- salesforce - 销售队伍数据表