1 概述
本篇文章主要與大家分享JqGrid插件參數問題。
2 參數詳解
2.1 初始化參數






2.2 ColModel參數










3 json數據
jqGrid可支持的數據類型:xml、json、jsonp、local or clientSide、xmlstring、jsonstring 、script、function (…)。
Json數據
需要定義jsonReader來跟服務器端返回的數據做對應,其默認值:
1 jsonReader : { 2 3 root: "rows", 4 5 page: "page", 6 7 total: "total", 8 9 records: "records", 10 11 repeatitems: true, 12 13 cell: "cell", 14 15 id: "id", 16 17 userdata: "userdata", 18 19 subgrid: { 20 21 root:"rows", 22 23 repeatitems: true, 24 25 cell:"cell" 26 27 }
這樣服務器端返回的數據格式:
1 { 2 3 total: "xxx", 4 page: "yyy", 5 6 records: "zzz", 7 8 rows : [ 9 10 {id:"1", cell:["cell11", "cell12", "cell13"]}, 11 12 {id:"2", cell:["cell21", "cell22", "cell23"]}, 13 14 ... 15 16 ] 17 18 }

1 jQuery("#gridid").jqGrid({ 2 3 ... 4 5 jsonReader : { 6 7 root:"invdata", 8 9 page: "currpage", 10 11 total: "totalpages", 12 13 records: "totalrecords", 14 15 cell: "invrow" 16 17 }, 18 19 ... 20 21 }); 22 23 totalpages: "xxx", 24 25 currpage: "yyy", 26 27 totalrecords: "zzz", 28 29 invdata : [ 30 31 {id:"1", invrow:["cell11", "cell12", "cell13"]}, 32 33 {id:"2", invrow:["cell21", "cell22", "cell23"]}, 34 35 ... 36 37 ]
repeatitems :指明每行的數據是可以重復的,如果設為false,則會從返回的數據中按名字來搜索元素,這個名字就是colModel中的名字
1 jsonReader : { 2 3 root:"invdata", 4 5 page: "currpage", 6 7 total: "totalpages", 8 9 records: "totalrecords", 10 11 repeatitems: false, 12 13 id: "0" 14 15 } 16 17 totalpages: "xxx", 18 19 currpage: "yyy", 20 21 totalrecords: "zzz", 22 23 invdata : [ 24 25 {invid:"1",invdate:"cell11", amount:"cell12", tax:"cell13", total:"1234", note:"somenote"}, 26 27 {invid:"2",invdate:"cell21", amount:"cell22", tax:"cell23", total:"2345", note:"some note"}, 28 29 ... 30 31 ]
此例中,id屬性值為“invid”。 一旦當此屬性設為false時,我們就不必把所有在colModel定義的name值都賦值。因為是按name來進行搜索元素的,所以他的排序也不是按colModel中指定的排序結果。
用戶數據(user data) 在某些情況下,我們需要從服務器端返回一些參數但並不想直接把他們顯示到表格中,而是想在別的地方顯示,那么我們就需要用到userdata標簽
1 jsonReader: { 2 3 ... 4 5 userdata: "userdata", 6 7 ... 8 9 } 10 11 { 12 13 total: "xxx", 14 15 page: "yyy", 16 17 records: "zzz", 18 19 userdata: {totalinvoice:240.00, tax:40.00}, 20 21 rows : [ 22 23 {id:"1", cell:["cell11", "cell12", "cell13"]}, 24 25 {id:"2", cell:["cell21", "cell22", "cell23"]}, 26 27 ... 28 29 ] 30 31 }
在客戶端我們可以有下面兩種方法得到這些額外信息:
1.jQuery("grid_id").getGridParam('userData')
2.jQuery("grid_id").getUserData()
3.jQuery("grid_id").getUserDataItem( key )
4 jqGrid事件
使用方法
1 var lastSel; 2 3 jQuery("#gridid").jqGrid({ 4 5 ... 6 7 onSelectRow: function(id){ 8 9 if(id && id!==lastSel){ 10 11 jQuery('#gridid').restoreRow(lastSel); 12 13 lastSel=id; 14 15 } 16 17 jQuery('#gridid').editRow(id, true); 18 19 }, 20 21 ... 22 23 })
1 var lastSel; 2 3 jQuery("#gridid").jqGrid({ 4 5 ... 6 7 onSelectRow: function(id){ 8 9 if(id && id!==lastSel){ 10 11 jQuery('#gridid').restoreRow(lastSel); 12 13 lastSel=id; 14 15 } 16 17 jQuery('#gridid').editRow(id, true); 18 19 }, 20 21 ... 22 23 })

5 jqGrid方法
jqGrid的方法,從3.6開始已經完全兼容jQuery UI庫。
jQuery("#grid_id").jqGridMethod( parameter1,...parameterN );
jQuery("#grid_id").setGridParam({...}).hideCol("somecol").trigger("reloadGrid");
如果使用新的API:
jQuery("#grid_id").jqGrid('method', parameter1,...parameterN );
jQuery("#grid_id").jqGrid('setGridParam',{...}).jqGrid('hideCol',"somecol").trigger("reloadGrid");
jqGrid配置使用新的api
1 !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 2 3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 4 5 <head> 6 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 8 9 <title>My First Grid</title> 10 11 12 13 <link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.7.1.custom.css" /> 14 15 <link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" /> 16 17 18 19 <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> 20 21 <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script> 22 23 <script type="text/javascript"> 24 25 jQuery.jgrid.no_legacy_api = true; 26 27 </script> 28 29 <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script> 30 31 32 33 </head> 34 35 <body> 36 37 ... 38 39 </body> 40 41 </html>


jqGrid的通用方法和設置
這些方法並不和jqGrid對象綁定,可以隨意使用:
jQuery.jgrid.jqGridFunction( parameter1,...parameterN );


6 翻頁操作
jqGrid的翻頁要定義在html里,通常是在grid的下面,且是一個div對象:
1 <table id="list"></table> 2 3 <div id="gridpager"></div> 4 5 jQuery("#grid_id").jqGrid({ 6 7 ... 8 9 pager : '#gridpager', 10 11 ... 12 13 });
不必給翻頁設置任何的css屬性。在jqGrid里定義的翻頁可以是::pager : '#gridpager', pager : 'gridpager' or pager : jQuery('#gridpager'). 推薦使用前兩個,當使用其他方式時jqGrid的導入導出功能時會引起錯誤。
導航欄的屬性:
1 $.jgrid = { 2 3 defaults : { 4 5 recordtext: "View {0} - {1} of {2}", 6 7 emptyrecords: "No records to view", 8 9 loadtext: "Loading...", 10 11 pgtext : "Page {0} of {1}" 12 13 }, 14 15 ... 16 17 }
如果想改變這些設置:
1 1. jQuery.extend(jQuery.jgrid.defaults,{emptyrecords: "Nothing to display",...}); 2 3 2. jQuery("#grid_id").jqGrid({ 4 5 ... 6 7 pager : '#gridpager', 8 9 emptyrecords: "Nothing to display", 10 11 ... 12 13 });

jQuery("#grid_id").setGridParam({rowNum:10}).trigger("reloadGrid");

1 <body> 2 3 ... 4 5 <table id="list"></table> 6 7 <div id="gridpager"></div> 8 9 ... 10 11 </body> 12 13 14 15 jQuery("#grid_id").jqGrid({ 16 17 ... 18 19 pager : '#gridpager', 20 21 ... 22 23 }); 24 25 jQuery("#grid_id").navGrid('#gridpager',{parameters},prmEdit, prmAdd, prmDel, prmSearch, prmView); 26 27 28 29 jQuery("#grid_id").jqGrid({ 30 31 ... 32 33 pager : '#gridpager', 34 35 ... 36 37 }); 38 39 jQuery("#grid_id").jqGrid('navGrid','#gridpager',{parameters},prmEdit, prmAdd, prmDel, prmSearch, prmView); 40 41 jQuery("#grid_id").jqGrid({ 42 43 ... 44 45 pager : '#gridpager', 46 47 ... 48 49 }).navGrid('#gridpager',{parameters}, prmEdit, prmAdd, prmDel, prmSearch, prmView); 50 51 ... 52 53 grid_id :表格id 54 55 gridpager :導航欄id 56 57 parameters :參數列表 58 59 prmEdit, prmAdd, prmDel, prmSearch, prmView :事件 60 61 $.jgrid = { 62 63 ... 64 65 search : { 66 67 caption: "Search...", 68 69 Find: "Find", 70 71 Reset: "Reset", 72 73 odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], 74 75 groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], 76 77 matchText: " match", 78 79 rulesText: " rules" 80 81 }, 82 83 edit : { 84 85 addCaption: "Add Record", 86 87 editCaption: "Edit Record", 88 89 bSubmit: "Submit", 90 91 bCancel: "Cancel", 92 93 bClose: "Close", 94 95 saveData: "Data has been changed! Save changes?", 96 97 bYes : "Yes", 98 99 bNo : "No", 100 101 bExit : "Cancel", 102 103 }, 104 105 view : { 106 107 caption: "View Record", 108 109 bClose: "Close" 110 111 }, 112 113 del : { 114 115 caption: "Delete", 116 117 msg: "Delete selected record(s)?", 118 119 bSubmit: "Delete", 120 121 bCancel: "Cancel" 122 123 }, 124 125 nav : { 126 127 edittext: "", 128 129 edittitle: "Edit selected row", 130 131 addtext:"", 132 133 addtitle: "Add new row", 134 135 deltext: "", 136 137 deltitle: "Delete selected row", 138 139 searchtext: "", 140 141 searchtitle: "Find records", 142 143 refreshtext: "", 144 145 refreshtitle: "Reload Grid", 146 147 alertcap: "Warning", 148 149 alerttext: "Please, select row", 150 151 viewtext: "", 152 153 viewtitle: "View selected row" 154 155 }, 156 157 ... 158


1 jQuery("#grid_id").jqGrid({ 2 3 ... 4 5 pager : '#gridpager', 6 7 ... 8 9 }).navGrid('#gridpager',{view:true, del:false}, 10 11 {}, // use default settings for edit 12 13 {}, // use default settings for add 14 15 {}, // delete instead that del:false we need this 16 17 {multipleSearch : true}, // enable the advanced searching 18 19 {closeOnEscape:true} /* allow the view dialog to be closed when user press ESC key*/ 20 21 );
7 自定義按鈕
1 jQuery("#grid_id").navGrid("#pager",...).navButtonAdd("#pager",{parameters}); 2 3 jQuery("#grid_id").jqGrid('navGrid',"#pager",...).jqGrid('navButtonAdd',"#pager",{parameters}); 4 5 { caption:"NewButton", buttonicon:"ui-icon-newwin", onClickButton:null, position: "last", title:"", cursor: "pointer"} 6 7 caption:按鈕名稱,可以為空,string類型 8 9 buttonicon:按鈕的圖標,string類型,必須為UI theme圖標 10 11 onClickButton:按鈕事件,function類型,默認null 12 13 position:first或者last,按鈕位置 14 15 title:string類型,按鈕的提示信息 16 17 cursor:string類型,光標類型,默認為pointer 18 19 id:string類型,按鈕id 20 21 如果設置多個按鈕: 22 23 jQuery("#grid_id") 24 25 .navGrid('#pager',{edit:false,add:false,del:false,search:false}) 26 27 .navButtonAdd('#pager',{ 28 29 caption:"Add", 30 31 buttonicon:"ui-icon-add", 32 33 onClickButton: function(){ 34 35 alert("Adding Row"); 36 37 }, 38 39 position:"last" 40 41 }) 42 43 .navButtonAdd('#pager',{ 44 45 caption:"Del", 46 47 buttonicon:"ui-icon-del", 48 49 onClickButton: function(){ 50 51 alert("Deleting Row"); 52 53 }, 54 55 position:"last" 56 57 }); 58 59 按鈕間的分隔 60 61 jQuery("#grid_id").navGrid("#pager",...).navButtonAdd("#pager",{parameters}).navSeparatorAdd("#pager",{separator_parameters}}; 62 63 默認參數: 64 65 {sepclass : “ui-separator”,sepcontent: ''} 66 67 sepclass:ui-jqgrid的屬性名 68 69 sepcontent:分隔符的內容.
8 數據格式化
jqGrid的格式化是定義在語言包中 $jgrid = { ... formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } ... 這些設置可以通過colModel中的formatoptions參數修改 jQuery("#grid_id").jqGrid({ ... colModel : [ ... {name:'myname', ... formatter:'number', ...}, ... ], ... }); 此實例是對名為“myname”的列進行格式化,格式化類是“number”,假如初始值為“1234.1”則格式化后顯示為“1 234.10” 。 如果給某列進行格式化: jQuery("#grid_id").jqGrid({ ... colModel : [ ... {name:'myname', ... formatter:'currency', formatoptions:{decimalSeparator:",", thousandsSeparator: ",", decimalPlaces: 2, prefix: "$ "} } , ... ], ... }); 這個設置會覆蓋語言包中的設置。 select類型的格式化實例: 原始數據 jQuery("#grid_id").jqGrid({ ... colModel : [ {name:'myname', edittype:'select', editoptions:{value:"1:One;2:Two"}} ... ], ... }); 使用格式化后 jQuery("#grid_id").jqGrid({ ... colModel : [ {name:'myname', edittype:'select', formatter:'select', editoptions:{value:"1:One;2:Two"}} ... ] ... }); 結果是,表格的數據值為1或者2但是現實的是One或者Two。 對超鏈接使用select類型的格式化: jQuery("#grid_id").jqGrid({ ... colModel: [ {name:'myname', edittype:'select', formatter:'select', formatoptions:{baseLinkUrl:'someurl.php', addParam: '&action=edit'}, ...} ... ] ... }); 得到http://localhost/someurl.php?id=123&action=edit 如果想改變id值則 jQuery("#grid_id").jqGrid({ ... colModel: [ {name:'myname', edittype:'select', formatter:'select', formatoptions:{baseLinkUrl:'someurl.php', addParam: '&action=edit', idName:'myid'}, ...} ... ] ... }); 得到http://localhost/someurl.php?myid=123&action=edit
jqGrid 自定義格式化
jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:currencyFmatter}, ... ] ... }); function currencyFmatter (cellvalue, options, rowObject) { // do something here return new_format_value } cellvalue:要被格式化的值 options:對數據進行格式化時的參數設置,格式為: { rowId: rid, colModel: cm} rowObject:行數據 數據的反格式化跟格式化用法相似. jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:currencyFmatter, unformat:unformatCurrency}, ... ] ... }); function currencyFmatter (cellvalue, options, rowObject) { return "$"+cellvalue; } function unformatCurrency (cellvalue, options) { return cellvalue.replace("$",""); } 表格中數據實際值為123.00,但是顯示的是$123.00; 我們使用getRowData ,getCell 方法取得的值是123.00。 創建通用的格式化函數 <script type="text/javascript"> jQuery.extend($.fn.fmatter , { currencyFmatter : function(cellvalue, options, rowdata) { return "$"+cellvalue; } }); jQuery.extend($.fn.fmatter.currencyFmatter , { unformat : function(cellvalue, options) { return cellvalue.replace("$",""); } }); </script> 具體使用: jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:currencyFmatter}, ... ] ... })
jqGrid 自定義格式化
jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:currencyFmatter}, ... ] ... }); function currencyFmatter (cellvalue, options, rowObject) { // do something here return new_format_value } cellvalue:要被格式化的值
options:對數據進行格式化時的參數設置,格式為: { rowId: rid, colModel: cm}
rowObject:行數據
數據的反格式化跟格式化用法相似. jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:currencyFmatter, unformat:unformatCurrency}, ... ] ... }); function currencyFmatter (cellvalue, options, rowObject) { return "$"+cellvalue; } function unformatCurrency (cellvalue, options) { return cellvalue.replace("$",""); }
表格中數據實際值為123.00,但是顯示的是$123.00; 我們使用getRowData ,getCell 方法取得的值是123.00。 創建通用的格式化函數
<script type="text/javascript"> jQuery.extend($.fn.fmatter , { currencyFmatter : function(cellvalue, options, rowdata) { return "$"+cellvalue; } }); jQuery.extend($.fn.fmatter.currencyFmatter , { unformat : function(cellvalue, options) { return cellvalue.replace("$",""); } }); </script> 具體使用: jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, align:"center", editable: true, formatter:currencyFmatter}, ... ] ... })
9 搜索操作
1 表格中所有的列都可以作為搜索條件。 2 3 所用到的語言包文件 4 5 $.jgrid = { 6 7 ... 8 9 search : { 10 11 caption: "Search...", 12 13 Find: "Find", 14 15 Reset: "Reset", 16 17 odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], 18 19 groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], 20 21 matchText: " match", 22 23 rulesText: " rules" 24 25 }

jQuery("#grid_id").jqGrid({ ... colModel: [ ... {name:'price', index:'price', width:60, search:true, stype:'text', searchoptions:{dataInit:datePick, attr:{title:'Select Date'}} }, ... ] ... }); datePick = function(elem) { jQuery(elem).datepicker(); } 需要說明的: 所有的搜索都是使用url來到服務器端查詢數據。 當執行搜索時會用查詢數據填充postData array 發送到服務器端搜索字符串的名稱為_search 當點擊刷新按鈕時不會使用搜索條件 每個搜索方法都有自己的數據清空方法
搜索工具欄

自定義搜索
<div id="mysearch"></div> jQuery("#mysearch").filterGrid('#grid_id',options);


10 配置json
1 IE8,FF3以及Chrome 3已經支持JSON,配置: 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 6 7 <head> 8 9 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 10 11 <title>My First Grid</title> 12 13 14 15 <link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.7.1.custom.css" /> 16 17 <link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" /> 18 19 20 21 <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> 22 23 <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script> 24 25 <script type="text/javascript"> 26 27 jQuery.jgrid.useJSON = true; 28 29 </script> 30 31 <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script> 32 33 34 35 </head> 36 37 <body> 38 39 ... 40 41 </body> 42 43 </html> 44 45 這段代碼要放到語言包之后jqGrid.js文件之前。 46 47 如果瀏覽器不支持JSON,那么我們只能用eval函數解析json。 48 49 除了jqGrid本身提供對json的類庫外,我們可以使用JSON.parse來處理JSON,配置如下: 50 51 52 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 53 54 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 55 56 <head> 57 58 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 59 60 <title>My First Grid</title> 61 62 63 64 <link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.7.1.custom.css" /> 65 66 <link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" /> 67 68 69 70 <script src="js/json2.js" type="text/javascript"></script> 71 72 <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script> 73 74 <script src="js/i18n/grid.locale-en.js" type="text/javascript"></script> 75 76 <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script> 77 78 <script type="text/javascript"> 79 80 jQuery.extend(jQuery.jgrid,{ 81 82 parse:function(jsstring) { 83 84 return JSON.parse(jsstring); 85 86 } 87 88 }); 89 90 </script> 91 92 93 94 </head> 95 96 <body> 97 98 ... 99 100 </body> 101 102 </html>
11 參考文獻
【01】http://blog.mn886.net/jqGrid/
12 版權
- 感謝您的閱讀,若有不足之處,歡迎指教,共同學習、共同進步。
- 博主網址:http://www.cnblogs.com/wangjiming/。
- 極少部分文章利用讀書、參考、引用、抄襲、復制和粘貼等多種方式整合而成的,大部分為原創。
- 如您喜歡,麻煩推薦一下;如您有新想法,歡迎提出,郵箱:2016177728@qq.com。
- 可以轉載該博客,但必須著名博客來源。
