我想保存jqGrid的状态(排序列,排序顺序,列宽,工具栏搜索字段),当用户离开网站并在他回到网站时恢复网格时。
我的第一次尝试是使用getGridParam
方法加载数据,然后使用JSON对其进行序列化,并将其作为JSON-String保存在cookie中。但是cookie没有足够的空间来保存gridParam。
所以我决定使用localstorage来保存Grid的状态。我的代码如下所示:
$(window).unload(function () {
// Load GridParam
var gridData = $('#Grid').jqGrid('getGridParam')};
// Serialize it to as JSON-String
var gridDataAsString = $.toJSON(gridData);
// Save the serialized Griddata in the localStorage
localStorage.setItem("GridParam", gridDataAsString);
});
这很好用。但是在下一步中我从localStroage加载GridParam并尝试恢复网格。加载数据也没问题。在调试模式下,我可以看到所有数据都是从localStorage正确加载的。但是,如果我想使用setGridParam
方法恢复网格,则网格具有所有默认值。我的代码如下所示:
$(document).ready(function () {
$("#Grid").jqGrid({ /* Initialize the grid with default values */ });
var loadedGridDataAsString = localStorage.getItem("GridParam");
// Use the default value if no data exists in localStorage
if (loadedGridDataAsString != null) {
// Deserialize the JSON-String to an object
var loadedGridData = $.evalJSON(loadedGridDataAsString);
$("#Grid").jqGrid('setGridParam', loadedGridData);
$("#Grid").trigger('reloadGrid');
}
}
答案 0 :(得分:6)
这就是我保存网格状态的方式(作为隐藏字段中的json数据,而不是localstorage,但想法应该是相同的)。
将网格参数保存为隐藏字段中的JSON:
function saveGridParameters(grid) {
var gridInfo = new Object();
gridInfo.url = grid.jqGrid('getGridParam', 'url');
gridInfo.sortname = grid.jqGrid('getGridParam', 'sortname');
gridInfo.sortorder = grid.jqGrid('getGridParam', 'sortorder');
gridInfo.selrow = grid.jqGrid('getGridParam', 'selrow');
gridInfo.page = grid.jqGrid('getGridParam', 'page');
gridInfo.rowNum = grid.jqGrid('getGridParam', 'rowNum');
gridInfo.postData = grid.jqGrid('getGridParam', 'postData');
gridInfo.search = grid.jqGrid('getGridParam', 'search');
$('#gridParams').val(JSON.stringify(gridInfo));
}
加载保存的数据:(我将保存的数据加载到网格的beforeRequest事件中):
beforeRequest: function() //loads the jqgrids state from before save
{
if(gridParams !=null && gridParams!="")
{
var gridInfo = $.parseJSON(gridParams);
var grid = $('#ReportPartsGrid');
grid.jqGrid('setGridParam', { url: gridInfo.url });
grid.jqGrid('setGridParam', { sortname: gridInfo.sortname });
grid.jqGrid('setGridParam', { sortorder: gridInfo.sortorder });
grid.jqGrid('setGridParam', { selrow: gridInfo.selrow });
grid.jqGrid('setGridParam', { page: gridInfo.page });
grid.jqGrid('setGridParam', { rowNum: gridInfo.rowNum });
grid.jqGrid('setGridParam', { postData: gridInfo.postData });
grid.jqGrid('setGridParam', { search: gridInfo.search });
gridParams = '';
$('#ReportPartsGrid').trigger('reloadGrid');
}
},