jQuery 记住(持久化)jqGrid的过滤器、排序顺序和当前页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3015203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:43:15  来源:igfitidea点击:

Remember (persist) the filter, sort order and current page of jqGrid

jquerycookiespersistencejqgridfiltering

提问by Jimbo

My application users asked if it were possible for pages that contain a jqGrid to remember the filter, sort order and current page of the grid (because when they click a grid item to carry out a task and then go back to it they'd like it to be "as they left it")

我的应用程序用户询问包含 jqGrid 的页面是否有可能记住网格的过滤器、排序顺序和当前页面(因为当他们单击网格项目执行任务然后返回到他们想要的它是“他们离开时”)

Cookiesseem to be the way forward, but how to get the page to load theseand set themin the grid beforeit makes its first data request is a little beyond me at this stage.

Cookies似乎是前进的方向,但是在这个阶段如何让页面加载这些它发出第一次数据请求之前将它们设置在网格中有点超出我的范围。

Does anyone have any experience with this kind of thing with jqGrid? Thanks!

有没有人对jqGrid有这种事情的经验?谢谢!

采纳答案by Jimbo

PROBLEM SOLVED

问题解决了

I eventually ended up using cookies in javascript to store the sort column, sort order, page number, grid rows and filter details of the grid (using JSON/Javascript cookies- the prefsobject)

我最终在 javascript 中使用 cookie 来存储排序列、排序顺序、页码、网格行和网格的过滤器详细信息(使用JSON/Javascript cookie-prefs对象)

Save Preferences- Called from $(window).unload(function(){ ... });

保存首选项- 调用自$(window).unload(function(){ ... });

var filters = {
    fromDate: $('#fromDateFilter').val(),
    toDate: $('#toDateFilter').val(),
    customer: $('#customerFilter').val()
};

prefs.data = {
    filter: filters,
    scol: $('#list').jqGrid('getGridParam', 'sortname'),
    sord: $('#list').jqGrid('getGridParam', 'sortorder'),
    page: $('#list').jqGrid('getGridParam', 'page'),
    rows: $('#list').jqGrid('getGridParam', 'rowNum')
};

prefs.save();

Load Preferences- Called from $(document).ready(function(){ ... });

加载首选项- 调用自$(document).ready(function(){ ... });

var gridprefs = prefs.load();

$('#fromDateFilter').val(gridprefs.filter.fromDate);
$('#toDateFilter').val(gridprefs.filter.toDate);
$('#customerFilter').val(gridprefs.filter.customer);

$('#list').jqGrid('setGridParam', {
    sortname: gridprefs.scol,
    sortorder: gridprefs.sord,
    page: gridprefs.page,
    rowNum: gridprefs.rows
});

// filterGrid method loads the jqGrid postdata with search criteria and re-requests its data
filterGrid();

jqGrid Reference: http://www.secondpersonplural.ca/jqgriddocs/_2eb0fi5wo.htm

jqGrid 参考:http: //www.secondpersonplural.ca/jqgriddocs/_2eb0fi5wo.htm

BY POPULAR DEMAND - THE FILTERGRID CODE

根据大众需求 - 过滤网代码

    function filterGrid() {
        var fields = "";
        var dateFrom = $('#dateFrom').val();
        var dateTo = $('#dateTo').val();

        if (dateFrom != "") fields += (fields.length == 0 ? "" : ",") + createField("shipmentDate", "ge", dateFrom);
        if (dateTo != "") fields += (fields.length == 0 ? "" : ",") + createField("shipmentDate", "le", dateTo);

        var filters = '"{\"groupOp\":\"AND\",\"rules\":[' + fields + ']}"';

        if (fields.length == 0) {
            $("#list").jqGrid('setGridParam', { search: false, postData: { "filters": ""} }).trigger("reloadGrid");
        } else {
            $("#list").jqGrid('setGridParam', { search: true, postData: { "filters": filters} }).trigger("reloadGrid");
        }

    }

    function createField(name, op, data) {
        var field = '{\"field\":\"' + name + '\",\"op\":\"' + op + '\",\"data\":\"' + data + '\"}';
        return field;
    }

回答by dlewicki

I was working on the same thing but also needed to get and save the column ordering. It's not simple as jqGrid.remapColumns is relative to what ever the current stat of the grid is...

我正在做同样的事情,但也需要获取和保存列排序。这并不简单,因为 jqGrid.remapColumns 与网格的当前统计数据有关......

Just in case anyone finds this helpful (and I'd love to know if there is already something to do this that I missed):

以防万一有人发现这有帮助(我很想知道是否已经有我错过的事情要做):

(function($){

$.jgrid.extend({

    getColumnOrder : function ()
    {
        var $grid = $(this);

        var colModel = $grid[0].p.colModel;

        var names = [];
        $.each(colModel, function(i,n){
            var name = this.name;
            if (name != "" && name != 'subgrid')
                names[names.length] = name;
        });

        return names;
        //return JSON.stringify(names);
        //$('#dbgout').val(j);

    },


    setColumnOrder : function (new_order)
    {
        var $grid = $(this);

        //var new_order = JSON.parse($('#dbgout').val());
        //new_order = ['a', 'c', 'd', 'b', 'e'];
        //              0    1    2    3    4

        var new_order_index = {};

        $.each(new_order, function(i,n){
            new_order_index[n] = i;
        });

        //new_order = ['a', 'c', 'd', 'b', 'e'];
        //              0    1    2    3    4
        // new_order_index a=>0 c=>1 d=>2 b=>3 e=>4

        var colModel = $grid[0].p.colModel;

        cur = [];
        $.each(colModel, function(i,n){
            var name = this.name;
            if (name != "" && name != 'subgrid')
                cur[cur.length] = name;
        });
        //cur = ['a', 'b', 'c', 'd', 'e'];
        //        0    1    2    3    4

        cur_index = {};
        $.each(cur, function(i,n){
            cur_index[n] = i;
        });


        // remapColumns: The indexes of the permutation array are the current order, the values are the new order.

        // new_order       0=>a 1=>c 2=>d 3=>b 4=>e
        // new_order_index a=>0 c=>1 d=>2 b=>3 e=>4

        // cur             0=>a 1=>b 2=>c 3=>d 4=>e
        // cur_index       a=>0 b=>1 c=>2 d=>3 e=>4

        // permutati       0    2    3    1    4
        //                 a    c    d    b    e
        var perm = [];
        $.each(cur, function(i, name){   // 2=>b

            new_item = new_order[i];     // c goes here
            new_item_index = cur_index[new_item];

            perm[i] = new_item_index;
        });

        if (colModel[0].name == 'subgrid' || colModel[0].name == '')
        {
            perm.splice(0, 0, 0);
            $.each(perm, function(i,n){
                ++perm[i]
            });
            perm[0] = 0;
        }

        $grid.jqGrid("remapColumns", perm, true, false);

    },



});
})(jQuery);

回答by Oleg

I part of work what you need you can implement with respect of jqGridExportand jqGridImport(see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:import_methods), but it seems to me you want more as exist out of the box in jqGrid. Some additional features you will have to implement yourself.

我的一部分工作是你需要你可以实现的jqGridExportjqGridImport(见http://www.trirand.com/jqgridwiki/doku.php?id=wiki:import_methods),但在我看来你想要更多的存在jqGrid 中的框。您必须自己实现一些附加功能。

回答by Justin Ethier

If the user logs in, you might be able to make AJAX requests back to the server when these parameters change. You could then save the settings, either to database (to make them permanent), to session (to persist them temporarily), or both (for performance reasons).

如果用户登录,当这些参数更改时,您可能能够将 AJAX 请求返回到服务器。然后,您可以将设置保存到数据库(使它们永久)、会话(暂时保留它们)或两者(出于性能原因)。

In any case, with the parameters stored server-side, you could just send them to the page when it is requested.

在任何情况下,通过服务器端存储的参数,您可以在请求时将它们发送到页面。

回答by ucefkh

Hi You can make this easier (no other dependency needed) in Pure Js not a jQuery plugin

嗨,您可以在 Pure Js 而非 jQuery 插件中简化此操作(不需要其他依赖项)

var prefs = {

    data: {},

    load: function () {
        var the_cookie = document.cookie.split(';');
        if (the_cookie[0]) {
            this.data = JSON.parse(unescape(the_cookie[0]));
        }
        return this.data;
    },

    save: function (expires, path) {
        var d = expires || new Date(2020, 02, 02);
        var p = path || '/';
        document.cookie = escape( JSON.stringify(this.data) )
                          + ';path=' + p
                          + ';expires=' + d.toUTCString();
    }

}

How to use ?

如何使用 ?

to_save = { "size": 40, "color": "green", "products":"jeans"};//and any other data/filters you wanna store here

prefs.data = to_save;
prefs.save();//now our json object is saved on the client document cookie


// delete
var date_in_the_past = new Date(2000,02,02);
prefs.save(date_in_the_past);


// read
var what = prefs.load();
// load populates prefs.data and also returns
alert(what.color);
// or ...
alert(prefs.data.color);

PS : All modern browsers support native JSON encoding/decoding (Internet Explorer 8+, Firefox 3.1+, Safari 4+, and Chrome 3+). Basically, JSON.parse(str) read more. PSS : the Object i used there is just optimization and removing the dependency of .toJSONstring ... source

PS:所有现代浏览器都支持原生 JSON 编码/解码(Internet Explorer 8+、Firefox 3.1+、Safari 4+ 和 Chrome 3+)。基本上, JSON.parse(str)阅读更多。PSS:我在那里使用的对象只是优化并删除了 .toJSONstring 的依赖...

Take a look at these jQuery plugins

看看这些 jQuery 插件

USE this don't use the custom funcation above https://github.com/carhartl/jquery-cookie

使用这个不要使用上面的自定义函数 https://github.com/carhartl/jquery-cookie

https://github.com/ScottHamper/Cookies

https://github.com/ScottHamper/Cookies