jQuery Datatable, saving state of the table like pagination, search etc

给你一囗甜甜゛ 提交于 2019-12-06 02:33:13
TGarrett

First off, you want to make sure you have a cookie, hop into chrome once you loaded your page, click on "settings," then "show advanced settings," under the privacy section click on content settings.

Below is a code example from that site, that works fine in my web app and also make sure you have the most recent version of the plugin.

$('#MyExampleGrv').dataTable({
    "bStateSave": true,
    "fnStateSave": function (oSettings, oData) {
        localStorage.setItem('DataTables_' + window.location.pathname, JSON.stringify(oData));
    },
    "fnStateLoad": function (oSettings) {
        var data = localStorage.getItem('DataTables_' + window.location.pathname);
        return JSON.parse(data);
    }
});

What this code does, is makes a local storage instead of the cookie, and uses a page specific versus just using a generic identifier called Datatables, this way if you have a table on another page, there will be no conflicts. What this code will not do, this code will not save the pagination state if you are using ASP.NET controls and a gridview, if you use the generic CRUD operations built into ASP.NET such as EDIT/DELETE/UPDATE, and your edit item is on pagination page 3, it will default to page 1 after postback and even partial postback via AJAX.

I know that this answer is not about this old version of datatables, but I believe it will help newcomers.

Datatables API changed a lot from 2011 to now. To save the state of a datatable, you use either HTML5 LocalStorage or DB(ajax callbacks). To enable state saving using localStorage, you do the following call:

$(document).ready(function() {
$('#datatable').DataTable({
  stateSave: true,
 });
} );

If you want to use sessionStorage instead of localStorage:

$(document).ready(function() {
$('#datatable').DataTable({
  stateSave: true,
  stateDuration:-1 //force the use of Session Storage
 });
} );

If you want to use a database to avoid storing them in the browser, then you have to use callback functions defined in the options stateSaveCallback and stateLoadCallback.

Here is a tutorial with examples and source code that shows you how to implement all the methods above: Datatables state save client and server-side

Do you see the cookie when inspecting in your browser? I am using Chrome and the developer tools to see the current cookies for the link you sent. I see a cookie called "datatables.net" stored on my machine. Do you see this cookie when trying your custom DataTables code?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!