起因
用datatable的table.ajax.url(’./get-data’).load()定时更新数据时,页面总是初始化,尤其是翻页过程中,页码总是伴随着刷新会跳转到第一页,影响用户的浏览体验。
解决方案
官方API中有stateSave配置项,理论上设置为stateSave: true,就可以解决,但实际效果不太理想,因为这个是指针对reload场合下才有效,如果是load的场合貌似就无效了。
Description
Enable or disable state saving. When enabled aDataTables will store state information such as pagination position, display length, filtering and sorting. When the end user reloads the page the table’s state will be altered to match what they had previously set up.
最佳方案
采用table.ajax.url(’./get-data’).load(null,false)或table.ajax.reload(null,false)的方式
ajax.reload( callback, resetPaging )
ajax.url().load( callback, resetPaging )
Parameters:
Name | Type | Optional |
---|---|---|
callback | function | Yes - default:null |
Function which is executed when the data has been reloaded and the table fully redrawn. The function is given a single parameter - the JSON data returned by the server, and expects no return. | ||
resetPaging | boolean | Yes - default:true |
Reset (default action or true) or hold the current paging position (false). A full re-sort and re-filter is performed when this method is called, which is why the pagination reset is the default action. |
Returns:
DataTables.Api
DataTables.Api instance
具体实践
**方法一**
// 初始化时写上获取数据的地址,但不要load加载
function initTableData() {
let table = $('#table').DataTable({……});
table.ajax.url('./get-data');
}
// 定期刷新中reload
function refreshInterval() {
table.ajax.reload(null,false);
}
**方法二**
// 或者无需初始化地址,直接每次刷新中写上请求地址,然后load加载
function refreshInterval() {
table.ajax.url('./get-data').load(null,false);
}