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

 

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