DataTables: Make url query string from table filter

时光毁灭记忆、已成空白 提交于 2019-12-03 07:48:50

dataTables has only built-in ability to save the state of a table locally, i.e in the localStorage / sessionStorage. If you want to pass an URL or link you must first be able to build an URL / link to pass, then make your page able to "restore" the dataTable based on the params passed in that URL / link.

Here is an extremely simple but yet working solution that are doing just that. It makes it possible to pass a static link to a user on the form

http://mywebsite.com?dtsearch=x&dtpage=3

and then the dataTable on the page will be restored to be filtering on x, showing page 3.

var DataTablesLinkify = function(dataTable) {
    this.dataTable = dataTable;
    this.url = location.protocol+'//'+location.host+location.pathname;
    this.link = function() {
        return this.url +
            '?dtsearch='+this.dataTable.search() +
            '&dtpage='+this.dataTable.page();
            //more params like current sorting column could be added here
    }
    //based on http://stackoverflow.com/a/901144/1407478
    this.getParam = function(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    this.restore = function() {
        var page = this.getParam('dtpage'), 
            search = this.getParam('dtsearch');
        if (search) this.dataTable.search(search).draw(false);
        if (page) this.dataTable.page(parseInt(page)).draw(false);
        //more params to take care of could be added here
    }
    this.restore();
    return this;
};

Usage :

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

To get a static link of the dataTables current state

var url = linkify.link()

As mentioned only searchstring / filter and page is included in the code above. But it is extremely easy to extend with ajax URL, page-length, current sorted column etc since it is taking advantage of the dataTables 1.10.x get / set methods.

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