jqGrid 实例中文版网址:http://blog.mn886.net/jqGrid/
国外官网:http://www.trirand.com/blog/jqgrid/jqgrid.html

http://free-jqgrid.github.io/

http://www.guriddo.net/demo/guriddojs/

http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs

http://www.guriddo.net/documentation/guriddo/javascript/

jqGrid是Trirand软件开发公司的Tony Tomov开发的一个方便人们开发使用的web组件,它包含了许多免费和开源的库如:jQuery, ThemeRoller, & jQuery UI等 ,同时最新的版本已经支持bootstrapUI,Tony最初的时候是因为他需要一种方式来表示数据库信息,这种方式有速度上的要求同时还要独立于服务器端技术和后台数据库,于是jqGrid诞生了,从最初的版本到现在已经升级到了Guriddo jqGrid 5.4 ,之前的各个版本都是在不断的修复bug以及添加符合需求的新功能。jqGrid越来越趋于完善。
————————————————

jqGrid 是一个用来显示网格数据的jQuery插件,通过使用jqGrid可以轻松实现前端页面与后台数据的ajax异步通信。

一、jqGrid特性

    • 基于jquery UI主题,开发者可以根据客户要求更换不同的主题。
    • 兼容目前所有流行的web浏览器。
    • Ajax分页,可以控制每页显示的记录数。
    • 支持XML,JSON,数组形式的数据源。
    • 提供丰富的选项配置及方法事件接口。
    • 支持表格排序,支持拖动列、隐藏列。
    • 支持滚动加载数据。
    • 支持实时编辑保存数据内容。
    • 支持子表格及树形表格。
    • 支持多语言。
    • 目前是免费的。

二、调用ajax的事件顺序如下:

  1. beforeRequest
  2. loadBeforeSend
  3. serializeGridData--从第4项开始为返回数据过程的事件
  4. loadError (if a error from the request occur - the event from steps 5 till 7 do not execute. If there is no error the event 4. does not execute and we continue to with the step 5.)
  5. beforeProcessing
  6. gridComplete
  7. loadComplete

三、JQgrid处理json数据

1、定义Jqgrid

  1. $("#tableOEE").jqGrid({
  2. data: [],
  3. datatype: "json",
  4. rownumbers: true, //显示行号
  5. loadonce:true,//在加载完成后,datatype自动变成local
  6. autowidth: true,
  7. pager: "#pager",
  8. viewrecords: true,//是否显示总记录数
  9. rowNum: 300,//表格中显示的记录数
  10. rowList: [10, 20, 30],
  11. height: '100%',
  12. gridview: true,//整个表格都构造完成后再添加到grid中。
  13. jsonReader:{repeatitems:false,id:"2"},//2表示id为rowData的第三个元素。
  14. beforeProcessing:function(res,status,errror){
  15. $.each(res.rows,function(i,n){//在来自Sever的数据Grid处理之前,格式化返回的JSON数据
  16. n.time=Number(n.time).toExponential(3);
  17. n.shift=["早","中","晚"][n.shift];
  18. });
  19. },
  20. loadComplete:function(xhr){//Grid加载完成后,可对Grid中的元素绑定事件了。分组完成。
  21. $("td.tdQty").bind("click", {}, getDcData);
  22. var rowCount=$(this).getGridParam("records");
  23. },
  24. colModel: [{ name: 'line', index: 'line', width: 80, align: 'center', label: '产线', key:true,editable:true },//排序sidx
  25. { name: 'shift', index: 'shift', width: 80, align: 'center', label: '班次' },
  26. { name: 'remark_avai', index: 'remark_avai', label: '备注', hidden: true },
  27. { name: 'qty_dot', index: 'qty_dot', align: 'right', classes: 'linkbyPop tdQty', label: '总点数', formatter: NumFmatter }, //formatter 格式化字段,unformat:反格式化。
  28. ]
  29. });
  30.  
  31. jQuery("#tableOEE").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: true, refresh: true },
  32. {}, //编辑edit参数
  33. {}, //添加add参数
  34. {}, //删除del参数
  35. { multipleSearch: true },//搜索search参数
  36. {closOnEscape:true}//查看view参数
  37. );
  38.  
  39. jQuery("#tableOEE").jqGrid('setGroupHeaders', {//表头分组
  40. useColSpanStyle: true,
  41. groupHeaders: [
  42. { startColumnName: 'time_avai', numberOfColumns: 1, titleText: '<em>A</em>' },
  43. { startColumnName: 'qty_dot', numberOfColumns: 3, titleText: '<em>F</em>' }]
  44. });

2、重新加载数据

  1. $("#tableOEE").jqGrid("clearGridData", true);
  2. $("#tableOEE").jqGrid("setGridParam", { data: {...} });
  3. //或者
  4. $("#tableOEE").setGridParam({ datatype: "json",url: "ajax/Punch.ashx",postData:"line=aa&lot=''"});
  5.  
  6. $("#tableOEE").trigger("reloadGrid");

3、后台处理

  1. ",rows=oeeList,records=oeeList.Count.ToString()};
  2. returnStr=new JavascriptSerialzer().Serilize(gridJson);

4、返回JSON格式:

1、当repeatitems:false时,名称要与colModel中的名字一致 。

  1. {"total":"10","page":"1","rows"=[{"line":"A1","Shift":3,"qty":123,"time":0.02}],"records":"4"} //records为查询出的总记录数,并非本页记录数。

2、如果repeatitems:true(默认)

  1. {"total":"10","page":"1","rows":[{id:"1",cell:["cell1","cell2"]},{id:"2",cell:["cell3","cell4"]}],"records":"4"}

对数字进行千分符分割:

  1. function getNumberSpliter(num) {
  2. if (num != '' && !isNaN(num)) {
  3. re = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g;
  4. n = String(num).replace(re, "$1,");
  5. return n;
  6. }
  7. else return num;
  8. }

四、JQgrid处理Local数据

  1. $("#tableOEE").jqGrid({
  2. data: [],
  3. datatype: "local",
  4. ...
  5. });
  6. //获得服务器数据
  7. $.ajax({
  8. type: "GET",
  9. cache: false,
  10. url: "ajax/Punch.ashx",
  11. data: i,
  12. success: function (res) {
  13. if (res.indexOf("SERVER_ERROR") == -1) {
  14. res = $.parseJSON(res);
  15. $.each(res, function (i, n) {
  16. this.shift = Shift[this.shift];
  17. this.time_perdot = Number(this.time_perdot).toExponential(3);
  18. });
  19. $("#tableOEE").jqGrid("clearGridData", true);
  20. $("#tableOEE").jqGrid("setGridParam", { data: res });
  21. $("#tableOEE").trigger("reloadGrid");
  22. $("td.tdQty").bind("click", {}, getDcData);//绑定grid中元素事件
  23. }
  24. else {
  25. alert(res.replace("SERVER_ERROR", "错误"));
  26. }
  27. $.unblockUI();
  28. },
  29. error: function (XMLHttpRequest, textStatus, errorThrown) {
  30. alert(textStatus + errorThrown);
  31. }
  32. });

五、JQgrid分组与行选择

  1. $("#tableOEE").jqGrid({
  2. grouping: true,
  3. groupingView: { groupField: ['BoxId'] },//分组
  4. multiselect: true,
  5. autowidth: true,
  6. //...
  7. colModel: [
  8. { name: 'Serial', index: 'Serial', align: 'center', label: '序列号' },
  9. { name: 'BoxId', index: 'BoxId', align: 'center', label: '箱号' },
  10. { name: 'progress_recid', key: true, index: 'progress_recid', width: 80, align: 'center', label: '内部号' }/
  11. //key: true主键,服务器返回的数据没有ID时,将此作为rowid使用。
  12. ],
  13. onSelectRow: selectRow
  14. });
  15.  
  16. var parentWidth = $("#DIV_Body").css("width").replace("px", "");
  17. $("#tableOEE").jqGrid("setGridWidth", parentWidth);
  18.  
  19. function selectRow(rowid, status, e) {
  20. if (status) {
  21. if ($("#tableOEE").getRowData(rowid).PalLocation != "在货仓") {
  22. $("#tableOEE").setSelection(rowid, false);//取消选择
  23. alert("在货仓状态的卡板,只能由SIS人员操作");
  24. }
  25.  
  26. var selRows = $("#tableOEE").getGridParam('selarrrow');//'selrow'最后选择行的主键
  27.  
  28. if (selRows.length > 2) {
  29. $("#tableOEE").setSelection(rowid, false);
  30. alert("只能选择两个序列号更换");
  31. }
  32. }
  33. }

六、 JQgrid构建查询

1、定义Jqgrid

ajax远端请求分页,排序,手工构建搜索参数,进行服务端查询,以及CURD操作。

  1. $(function () {
  2. $("#grid").jqGrid({
  3. url: "/PushPDA/GetTodoLists",
  4. datatype: 'json',
  5. mtype: 'Get',
  6. colNames: ['操作', 'ID', 'IP', '所属人', '生产线', '状态', '类型', '更新日期', '更新时间'],
  7. colModel: [
  8. { name: 'act', index: 'act', align: 'center', width: 80, search: false, sortable: false, editable: false },
  9. { hidden: true, align: 'center', name: 'ID', index: 'ID', editable: true, key: true },
  10. { name: 'IP', align: 'center', index: 'IP', editable: true },
  11. { name: 'Owner', align: 'center', index: 'Owner', editable: true },
  12. { name: 'Line', align: 'center', index: 'Line', editable: true },
  13. { name: 'Status', align: 'center', index: 'Status', editable: true, },
  14. { name: 'Type', align: 'center', index: 'Type', editable: true, edittype: 'select', formatter: 'select', editoptions: { value: { 'CASE': '套料', 'BIG': '中大件料' } } },
  15. { name: 'UpdateDate', align: 'center', index: 'UpdateDate', editable: false },
  16. { name: 'UpdateTime', align: 'center', index: 'UpdateTime', editable: false }
  17. ],
  18. pager: jQuery('#pager'),
  19. rowNum: 100,
  20. rowList: [10, 20, 30, 40],
  21. height: '100%',
  22. viewrecords: true,
  23. emptyrecords: 'No records to display',
  24. jsonReader: {
  25. root: "rows",
  26. page: "page",
  27. total: "total",
  28. records: "records",
  29. repeatitems: false,
  30. Id: "0"
  31. },
  32. autowidth: true,
  33. multiselect: false,
  34. beforeProcessing: function (res) {//格式化返回数据
  35. if (!res)
  36. return;
  37. //$.each(res.rows, function (i, n) {
  38. // n.UpdateDate = DatefromJSON(n.UpdateDate);
  39. // n.UpdateTime = secondToTimeString(n.UpdateTime);
  40. //});
  41. },
  42. gridComplete: function () {
  43. var ids = $("#grid").getDataIDs();//jqGrid('getDataIDs');
  44. for (var i = 0; i < ids.length; i++) {
  45. var cl = ids[i];
  46. be = "<input style='height:22px;width:40px;' type='button' value='编辑' onclick=\"jQuery('#grid').jqGrid('editGridRow','" + cl + "',{url: '/PushPDA/Edit',checkOnSubmit:true,checkOnUpdate:true,closeAfterEdit:true,closeOnEscape:true});\" />";
  47. de = "<input style='height:22px;width:40px;' type='button' value='删除' onclick=\"jQuery('#grid').jqGrid('delGridRow','" + cl + "',{ url: '/PushPDA/Delete', closeOnEscape:true});\" />";
  48. jQuery("#grid").jqGrid('setRowData', ids[i], { act: be + de });
  49. }
  50. },
  51. }).navGrid('#pager', { edit: true, add: true, del: true, search: false, refresh: true },
  52. {
  53. // edit options
  54. zIndex: 100,
  55. url: '/PushPDA/Edit',
  56. closeOnEscape: true,
  57. closeAfterEdit: true,
  58. recreateForm: true,
  59. afterComplete: function (response) {
  60. if (response.responseText) {
  61. alert(response.responseText);
  62. }
  63. }
  64. },
  65. {
  66. // add options
  67. zIndex: 100,
  68. url: "/PushPDA/Create",
  69. closeOnEscape: true,
  70. closeAfterAdd: true,
  71. afterComplete: function (response) {
  72. if (response.responseText) {
  73. alert(response.responseText);
  74. }
  75. }
  76. },
  77. {
  78. // delete options
  79. zIndex: 100,
  80. url: "/PushPDA/Delete",
  81. closeOnEscape: true,
  82. closeAfterDelete: true,
  83. recreateForm: true,
  84. msg: "Are you sure you want to delete this task?",
  85. afterComplete: function (response) {
  86. if (response.responseText) {
  87. alert(response.responseText);
  88. }
  89. }
  90. });
  91. new_search();
  92. });
  93.  
  94. //将整数秒格式转成时间格式。
  95. function secondToTimeString(seconds) {
  96. if (seconds == null) return "";
  97. var hh = parseInt(seconds / 3600).toString();
  98. seconds -= hh * 3600;
  99. var mm = Math.round(seconds / 60).toString();
  100. if (hh.length == 1) {
  101. hh = "0" + hh;
  102. }
  103. if (mm.length == 1) {
  104. mm = "0" + mm;
  105. }
  106. return hh + ":" + mm;
  107. }
  108.  
  109. //解析JOSN返回的日期字符串格式。
  110. function DatefromJSON(jsonstr) {
  111. // return eval (jsonstr.replace(new RegExp('/Date\\((-?[0-9]+)\\)/','g'),'new Date($1)')).toLocalDateString();
  112. if (jsonstr == null) return "";
  113. d = eval('new ' + (jsonstr.replace(/\//g, '')));
  114. var month = (d.getMonth() + 1);
  115. month = ("00" + month).substr(("" + month).length);
  116. var day = d.getDate()
  117. day = ("00" + day).substr(("" + day).length);
  118. return d.getFullYear() + "-" + month + "-" + day;
  119. }

2、手工构建查询参数

(1)单字段搜索:

主要构建的查询参数为searchField,searchString,searchOper

  1. var searchPara = { // 构建查询需要的参数
  2. searchField: "Line",
  3. searchString: strLines,
  4. searchOper: "in"
  5. };
  6. // 获得当前postData选项的值
  7. var postData = $("#grid").jqGrid("getGridParam", "postData");
  8. // 将查询参数融入postData选项对象
  9. $.extend(postData, searchPara);
  10. $("#grid").jqGrid("setGridParam", {
  11. url: "/PushPDA/GetTodoLists",
  12. search: true //将jqGrid的search选项设为true
  13. }).trigger("reloadGrid", [{ page: 1 }]); // 重新载入Grid表格,以使上述设置生效

(2)多字段搜索

主要构建的查询参数为groupOp,rules,filed,op,data.

  1. var rules = "";
  2. // 构建查询需要的参数
  3. var searchField = "Line";
  4. var searchString = strLines;
  5. var searchOper = "in";
  6. if (searchField && searchOper && searchString) { //如果三者皆有值且长度大于0,则将查询条件加入rules字符串
  7. rules += ',{"field":"' + searchField + '","op":"' + searchOper + '","data":"' + searchString + '"}';
  8. }
  9. if (strDate1) {
  10. rules += ',{"field":" IP","op":"eq","data":"' + strDate1 + '"}';
  11. }
  12. if (rules) { //如果rules不为空,且长度大于0,则去掉开头的逗号
  13. rules = rules.substring(1);
  14. }
  15. //串联好filtersStr字符串
  16. var filtersStr = '{"groupOp":"AND","rules":[' + rules + ']}';
  17. // 获得当前postData选项的值
  18. var postData = $("#grid").jqGrid("getGridParam", "postData");
  19. // 将查询参数融入postData选项对象
  20. $.extend(postData, { filters: filtersStr });
  21. $("#grid").jqGrid("setGridParam", {
  22. url: "/PushPDA/GetTodoLists",
  23. search: true // 将jqGrid的search选项设为true
  24. }).trigger("reloadGrid", [{ page: 1 }]); // (7)重新载入Grid表格,以使上述设置生效

3、后台根据查询条件返回查询结果

注意使用Linq语句,以及动态Linq查询。

  1. public JsonResult GetTodoLists(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchString, string searchOper, string filters) //Gets the todo Lists.
  2. {
  3. IQueryable<PushPdaInfo> pdas = db.PushPDAs;
  4. IQueryable<PushPdaInfo> todoListsResults = null;
  5. //搜索
  6. if (_search)
  7. {
  8. if (!string.IsNullOrEmpty(searchField))//单字段搜索
  9. {
  10. todoListsResults = pdas.Where(p => searchString.IndexOf(p.Line) > -);
  11. }
  12. else if (!string.IsNullOrEmpty(filters))//多字段搜索
  13. {
  14. JObject ofilters = JObject.Parse(filters);
  15. string searchField1;
  16. string searchString1;
  17. string sql;
  18. ; i < ofilters["rules"].Count(); i++)
  19. {
  20. searchField1 = ofilters["rules"][i]["field"].ToString();
  21. searchString1 = ofilters["rules"][i]["data"].ToString();
  22. sql = "\"" + searchString1 + "\".Contains(" + searchField1 + ")";
  23. todoListsResults = pdas.Where(sql);
  24. }
  25. }
  26. }
  27. else
  28. {
  29. return Json(new { }, JsonRequestBehavior.AllowGet);
  30. }
  31. //排序
  32. if (string.IsNullOrEmpty(sidx)) sidx = "IP";
  33. todoListsResults = todoListsResults.OrderBy(sidx + " " + sord);
  34. //分页
  35. ;
  36. int pageSize = rows;
  37. int totalRecords = pdas.Count();
  38. var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
  39. todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
  40. var todoListsResults1 = from p in todoListsResults.ToList()
  41. select new
  42. {
  43. p.ID,
  44. p.IP,
  45. p.Owner,
  46. p.Line,
  47. p.Status,
  48. p.Type,
  49. UpdateDate = p.UpdateDate.HasValue ? p.UpdateDate.GetValueOrDefault().ToShortDateString() : "",
  50. UpdateTime = p.UpdateTime.HasValue ? IntTimeToStringTime(p.UpdateTime.GetValueOrDefault()) : ""
  51. };
  52. var jsonData = new
  53. {
  54. total = totalPages,
  55. page,
  56. records = totalRecords,
  57. rows = todoListsResults1
  58. };
  59. return Json(jsonData, JsonRequestBehavior.AllowGet);
  60. }

4、定义HTML

  1. <div id="search_container" title="Search Options">
  2. <div id="boxbody">
  3. <fieldset>
  4. <legend>Query IP<span id="spanClearDates">[Clear]</span></legend>
  5. <table>
  6. <tr>
  7. <td><strong>扫描枪IP: </strong>
  8. <input id="Text_Date1" type="text" />
  9. </td>
  10. </tr>
  11. </table>
  12. </fieldset>
  13. </div>
  14. </div>
  15. <div>
  16. <table id="grid"></table>
  17. <div id="pager"></div>
  18. </div>

JQgrid处理json数据的更多相关文章

  1. 关于jqGrig如何写自定义格式化函数将JSON数据的字符串转换为表格各个列的值

    首先介绍一下jqGrid是一个jQuery的一个表格框架,现在有一个需求就是将数据库表的数据拿出来显示出来,分别有id,name,details三个字段,其中难点就是details字段,它的数据是这样 ...

  2. 【转】Jqgrid学习之数据

    jqGrid可支持的数据类型:xml.json.jsonp.local or clientSide.xmlstring.jsonstring .script.function (…). Json数据 ...

  3. 使用TSQL查询和更新 JSON 数据

    JSON是一个非常流行的,用于数据交换的文本数据(textual data)格式,主要用于Web和移动应用程序中.JSON 使用“键/值对”(Key:Value pair)存储数据,能够表示嵌套键值对 ...

  4. 利用Python进行数据分析(2) 尝试处理一份JSON数据并生成条形图

    一.JSON 数据准备 首先准备一份 JSON 数据,这份数据共有 3560 条内容,每条内容结构如下: 本示例主要是以 tz(timezone 时区) 这一字段的值,分析这份数据里时区的分布情况. ...

  5. Salesforce Apex 使用JSON数据的示例程序

    本文介绍了一个在Salesforce Apex中使用JSON数据的示例程序, 该示例程序由以下几部分组成: 1) Album.cls, 定了了封装相关字段的数据Model类 2) RestClient ...

  6. MVC使用ajax异步刷新时怎样输出从后台中传过来的JSON数据

    前言 这几天在学习MVC使用AJAX异步刷,因为是新手.所以在js中传参数到后台以及后台返回数据到前台怎么接受,怎么前台遍历出JSON数据都开始不知道,相信新手在使用时跟我一样会遇到,这里我就和大家分 ...

  7. ASP.NET提取多层嵌套json数据的方法

    本文实例讲述了ASP.NET利用第三方类库Newtonsoft.Json提取多层嵌套json数据的方法,具体例子如下. 假设需要提取的json字符串如下: {"name":&quo ...

  8. jQuey知识点三 解析json数据

    1.解析简单数据 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="vie ...

  9. JSON数据的使用

    JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧. JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON ...

随机推荐

  1. C语言中malloc、free和new、delete的用法和区别

    很多学过C的人对malloc都不是很了解,知道使用malloc要加头文件,知道malloc是分配一块连续的内存,知道和free函数是一起用的.但是但是: 一部分人还是将:malloc当作系统所提供的或 ...

  2. 编译Cython代码时遇到的问题: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

    使用python setup.py build_ext --inplace命令编译cython代码, 出现以下错误: Compiling cython_example.pyx because it c ...

  3. 通过noVNC和websockify连接到QEMU/KVM 转

    开源项目 QEMU.KVM.libvirt 实现了创建虚拟机,启动虚拟机,监控虚拟机.我们解决了从无到有的问题,这时就该考虑从有到优了.尽管我们能使用 SSH 的方式来登录使用虚拟机,但这种方式从感觉 ...

  4. jenkins publish .net core application to linux server

    最近学习Docker与Jenkins, 网上大部分都是关于Jenkins+Git+Docker进行持续远程部署, 我一直在考虑为什么Jenkins和Docker要绑定一块使用, 因为我想单独使用Jen ...

  5. Linux7 安装python3.5.4

    1.首先修改yum配置文件 因为yum使用python2,因此替换为python3后可能无法正常工作,继续使用这个python2.7.5 因此修改yum配置文件(vi /usr/bin/yum). 把 ...

  6. C++ 数组和vector的基本操作

    1.静态数组的基本操作 int a[5] = {0, 3, 4, 6, 2}; 1.1 数组的遍历 1.1.1 传统的for循环遍历 int size = sizeof(a) / sizeof(*a) ...

  7. flex左右布局 左边固定 右侧自适应

    flex左右布局 左边固定 右侧自适应 想要保证自适应内容不超出容器怎么办. 通过为自适应的一侧设置width: 0;或者overflow: hidden;解决. 首先实现标题的布局,也很简单: &l ...

  8. 【SQL Server DBA】维护语句:删除并创建外键约束、获取建表语句

    原文:[SQL Server DBA]维护语句:删除并创建外键约束.获取建表语句 1.删除外键约束,建立外键约束 先建立3个表: /* drop table tb drop table tb_b dr ...

  9. windows + Eclipse 汉化

    https://www.eclipse.org/babel/downloads.php 下载Eclipse 对应版本 汉化包解压 复制文件夹里的内容到eclipse 文件夹下对应的文件里 重启ecli ...

  10. .net core 3.0更改默认身份认证的的表。

    public class ApplicationDbContext : IdentityDbContext<WebUser, WebRole, Guid, WebUserClaim, WebUs ...