datatables 重新加载表格 页数不变

datatables使用服务器模式,重新加载数据。每次都会回到第一页,现在想留在当前页并重载数据。

看官方文档: https://datatables.net/reference/api/ajax.reload()

 

unction ajax.reload( callback, resetPaging )

Parameters:

  Name Type Optional
1 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.

2 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

Examples

Reload the table data every 30 seconds (paging reset):

 

Javascript

1

2

3

4

5

6

7

var table = $('#example').DataTable( {

    ajax: "data.json"

} );

 

setInterval( function () {

    table.ajax.reload();

}, 30000 );

Reload the table data every 30 seconds (paging retained):

 

Javascript

1

2

3

4

5

6

7

var table = $('#example').DataTable( {

    ajax: "data.json"

} );

 

setInterval( function () {

    table.ajax.reload( nullfalse ); // user paging is not reset on reload

}, 30000 );

Use the callback to update an external elements:

 

Javascript

1

2

3

4

5

var table = $('#example').DataTable();

 

table.ajax.reload( function ( json ) {

    $('#myInput').val( json.lastInput );

} );

 

使用 table.ajax.reload( nullfalse );即可。第一个参数是加载成功的回调函数,第二个参数是是否重置页数,这里设为false。

如果需要带其他参数则可以使用

oTable.settings()[0].ajax.data = {age:17,name:'李白'};

我这边封装成一个方法使用


/**
 * 重新加载表格
 * @param selector table对象或者table的jq选择器
 * @param param  重新加载数据所带的参数
 */
function reload(selector,param){
    var oTable;

    if (!selector){
        selector = "table";
    }
    //jq搜索元素
    if (typeof(selector) == 'string'){
        oTable = $(selector).DataTable();
    }else{
        oTable = selector;
    }

    if (param){
        oTable.settings()[0].ajax.data = param;
    }
    oTable.ajax.reload(null, false);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章