【Jquery系列】JqGrid参数详解

来源:互联网 发布:windows 预览体验成员 编辑:程序博客网 时间:2024/05/29 19:40

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。
  • 可以转载该博客,但必须著名博客来源。