Jquery使用JQgrid組件處理json數(shù)據(jù)
jqGrid 實(shí)例中文版網(wǎng)址:http://blog.mn886.net/jqGrid/
國(guó)外官網(wǎng):http://www.trirand.com/blog/jqgrid/jqgrid.html
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軟件開(kāi)發(fā)公司的Tony Tomov開(kāi)發(fā)的一個(gè)方便人們開(kāi)發(fā)使用的web組件,它包含了許多免費(fèi)和開(kāi)源的庫(kù)如:jQuery, ThemeRoller, & jQuery UI等 ,同時(shí)最新的版本已經(jīng)支持bootstrapUI,Tony最初的時(shí)候是因?yàn)樗枰环N方式來(lái)表示數(shù)據(jù)庫(kù)信息,這種方式有速度上的要求同時(shí)還要獨(dú)立于服務(wù)器端技術(shù)和后臺(tái)數(shù)據(jù)庫(kù),于是jqGrid誕生了,從最初的版本到現(xiàn)在已經(jīng)升級(jí)到了Guriddo jqGrid 5.4 ,之前的各個(gè)版本都是在不斷的修復(fù)bug以及添加符合需求的新功能。jqGrid越來(lái)越趨于完善。
jqGrid 是一個(gè)用來(lái)顯示網(wǎng)格數(shù)據(jù)的jQuery插件,通過(guò)使用jqGrid可以輕松實(shí)現(xiàn)前端頁(yè)面與后臺(tái)數(shù)據(jù)的ajax異步通信。
一、jqGrid特性
- 基于jquery UI主題,開(kāi)發(fā)者可以根據(jù)客戶(hù)要求更換不同的主題。
- 兼容目前所有流行的web瀏覽器。
- Ajax分頁(yè),可以控制每頁(yè)顯示的記錄數(shù)。
- 支持XML,JSON,數(shù)組形式的數(shù)據(jù)源。
- 提供豐富的選項(xiàng)配置及方法事件接口。
- 支持表格排序,支持拖動(dòng)列、隱藏列。
- 支持滾動(dòng)加載數(shù)據(jù)。
- 支持實(shí)時(shí)編輯保存數(shù)據(jù)內(nèi)容。
- 支持子表格及樹(shù)形表格。
- 支持多語(yǔ)言。
- 目前是免費(fèi)的。
二、調(diào)用ajax的事件順序如下:
- beforeRequest
- loadBeforeSend
- serializeGridData--從第4項(xiàng)開(kāi)始為返回?cái)?shù)據(jù)過(guò)程的事件
- 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.)
- beforeProcessing
- gridComplete
- loadComplete
三、JQgrid處理json數(shù)據(jù)
1、定義Jqgrid
$("#tableOEE").jqGrid({ data: [], datatype: "json", rownumbers: true, //顯示行號(hào) loadonce:true,//在加載完成后,datatype自動(dòng)變成local autowidth: true, pager: "#pager", viewrecords: true,//是否顯示總記錄數(shù) rowNum: 300,//表格中顯示的記錄數(shù) rowList: [10, 20, 30], height: '100%', gridview: true,//整個(gè)表格都構(gòu)造完成后再添加到grid中。 jsonReader:{repeatitems:false,id:"2"},//2表示id為rowData的第三個(gè)元素。 beforeProcessing:function(res,status,errror){ $.each(res.rows,function(i,n){//在來(lái)自Sever的數(shù)據(jù)Grid處理之前,格式化返回的JSON數(shù)據(jù) n.time=Number(n.time).toExponential(3); n.shift=["早","中","晚"][n.shift]; }); }, loadComplete:function(xhr){//Grid加載完成后,可對(duì)Grid中的元素綁定事件了。分組完成。 $("td.tdQty").bind("click", {}, getDcData); var rowCount=$(this).getGridParam("records"); }, colModel: [{ name: 'line', index: 'line', width: 80, align: 'center', label: '產(chǎn)線(xiàn)', key:true,editable:true },//排序sidx { name: 'shift', index: 'shift', width: 80, align: 'center', label: '班次' }, { name: 'remark_avai', index: 'remark_avai', label: '備注', hidden: true }, { name: 'qty_dot', index: 'qty_dot', align: 'right', classes: 'linkbyPop tdQty', label: '總點(diǎn)數(shù)', formatter: NumFmatter }, //formatter 格式化字段,unformat:反格式化。 ] }); jQuery("#tableOEE").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: true, refresh: true }, {}, //編輯edit參數(shù) {}, //添加add參數(shù) {}, //刪除del參數(shù) { multipleSearch: true },//搜索search參數(shù) {closOnEscape:true}//查看view參數(shù) ); jQuery("#tableOEE").jqGrid('setGroupHeaders', {//表頭分組 useColSpanStyle: true, groupHeaders: [ { startColumnName: 'time_avai', numberOfColumns: 1, titleText: '<em>A</em>' }, { startColumnName: 'qty_dot', numberOfColumns: 3, titleText: '<em>F</em>' }] });
2、重新加載數(shù)據(jù)
$("#tableOEE").jqGrid("clearGridData", true); $("#tableOEE").jqGrid("setGridParam", { data: {...} }); //或者 $("#tableOEE").setGridParam({ datatype: "json",url: "ajax/Punch.ashx",postData:"line=aa&lot=''"}); $("#tableOEE").trigger("reloadGrid");
3、后臺(tái)處理
var GridJson=new { total="10",page="1",rows=oeeList,records=oeeList.Count.ToString()}; returnStr=new JavascriptSerialzer().Serilize(gridJson);
4、返回JSON格式:
1、當(dāng)repeatitems:false時(shí),名稱(chēng)要與colModel中的名字一致 。
{"total":"10","page":"1","rows"=[{"line":"A1","Shift":3,"qty":123,"time":0.02}],"records":"4"} //records為查詢(xún)出的總記錄數(shù),并非本頁(yè)記錄數(shù)。
2、如果repeatitems:true(默認(rèn))
{"total":"10","page":"1","rows":[{id:"1",cell:["cell1","cell2"]},{id:"2",cell:["cell3","cell4"]}],"records":"4"}
對(duì)數(shù)字進(jìn)行千分符分割:
function getNumberSpliter(num) { if (num != '' && !isNaN(num)) { re = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g; n = String(num).replace(re, "$1,"); return n; } else return num; }
四、JQgrid處理Local數(shù)據(jù)
$("#tableOEE").jqGrid({ data: [], datatype: "local", ... }); //獲得服務(wù)器數(shù)據(jù) $.ajax({ type: "GET", cache: false, url: "ajax/Punch.ashx", data: i, success: function (res) { if (res.indexOf("SERVER_ERROR") == -1) { res = $.parseJSON(res); $.each(res, function (i, n) { this.shift = Shift[this.shift]; this.time_perdot = Number(this.time_perdot).toExponential(3); }); $("#tableOEE").jqGrid("clearGridData", true); $("#tableOEE").jqGrid("setGridParam", { data: res }); $("#tableOEE").trigger("reloadGrid"); $("td.tdQty").bind("click", {}, getDcData);//綁定grid中元素事件 } else { alert(res.replace("SERVER_ERROR", "錯(cuò)誤")); } $.unblockUI(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + errorThrown); } });
五、JQgrid分組與行選擇
$("#tableOEE").jqGrid({ grouping: true, groupingView: { groupField: ['BoxId'] },//分組 multiselect: true, autowidth: true, //... colModel: [ { name: 'Serial', index: 'Serial', align: 'center', label: '序列號(hào)' }, { name: 'BoxId', index: 'BoxId', align: 'center', label: '箱號(hào)' }, { name: 'progress_recid', key: true, index: 'progress_recid', width: 80, align: 'center', label: '內(nèi)部號(hào)' }/ //key: true主鍵,服務(wù)器返回的數(shù)據(jù)沒(méi)有ID時(shí),將此作為rowid使用。 ], onSelectRow: selectRow }); var parentWidth = $("#DIV_Body").css("width").replace("px", ""); $("#tableOEE").jqGrid("setGridWidth", parentWidth); function selectRow(rowid, status, e) { if (status) { if ($("#tableOEE").getRowData(rowid).PalLocation != "在貨倉(cāng)") { $("#tableOEE").setSelection(rowid, false);//取消選擇 alert("在貨倉(cāng)狀態(tài)的卡板,只能由SIS人員操作"); } var selRows = $("#tableOEE").getGridParam('selarrrow');//'selrow'最后選擇行的主鍵 if (selRows.length > 2) { $("#tableOEE").setSelection(rowid, false); alert("只能選擇兩個(gè)序列號(hào)更換"); } } }
六、 JQgrid構(gòu)建查詢(xún)
1、定義Jqgrid
ajax遠(yuǎn)端請(qǐng)求分頁(yè),排序,手工構(gòu)建搜索參數(shù),進(jìn)行服務(wù)端查詢(xún),以及CURD操作。
$(function () { $("#grid").jqGrid({ url: "/PushPDA/GetTodoLists", datatype: 'json', mtype: 'Get', colNames: ['操作', 'ID', 'IP', '所屬人', '生產(chǎn)線(xiàn)', '狀態(tài)', '類(lèi)型', '更新日期', '更新時(shí)間'], colModel: [ { name: 'act', index: 'act', align: 'center', width: 80, search: false, sortable: false, editable: false }, { hidden: true, align: 'center', name: 'ID', index: 'ID', editable: true, key: true }, { name: 'IP', align: 'center', index: 'IP', editable: true }, { name: 'Owner', align: 'center', index: 'Owner', editable: true }, { name: 'Line', align: 'center', index: 'Line', editable: true }, { name: 'Status', align: 'center', index: 'Status', editable: true, }, { name: 'Type', align: 'center', index: 'Type', editable: true, edittype: 'select', formatter: 'select', editoptions: { value: { 'CASE': '套料', 'BIG': '中大件料' } } }, { name: 'UpdateDate', align: 'center', index: 'UpdateDate', editable: false }, { name: 'UpdateTime', align: 'center', index: 'UpdateTime', editable: false } ], pager: jQuery('#pager'), rowNum: 100, rowList: [10, 20, 30, 40], height: '100%', viewrecords: true, emptyrecords: 'No records to display', jsonReader: { root: "rows", page: "page", total: "total", records: "records", repeatitems: false, Id: "0" }, autowidth: true, multiselect: false, beforeProcessing: function (res) {//格式化返回?cái)?shù)據(jù) if (!res) return; //$.each(res.rows, function (i, n) { // n.UpdateDate = DatefromJSON(n.UpdateDate); // n.UpdateTime = secondToTimeString(n.UpdateTime); //}); }, gridComplete: function () { var ids = $("#grid").getDataIDs();//jqGrid('getDataIDs'); for (var i = 0; i < ids.length; i++) { var cl = ids[i]; 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});\" />"; de = "<input style='height:22px;width:40px;' type='button' value='刪除' onclick=\"jQuery('#grid').jqGrid('delGridRow','" + cl + "',{ url: '/PushPDA/Delete', closeOnEscape:true});\" />"; jQuery("#grid").jqGrid('setRowData', ids[i], { act: be + de }); } }, }).navGrid('#pager', { edit: true, add: true, del: true, search: false, refresh: true }, { // edit options zIndex: 100, url: '/PushPDA/Edit', closeOnEscape: true, closeAfterEdit: true, recreateForm: true, afterComplete: function (response) { if (response.responseText) { alert(response.responseText); } } }, { // add options zIndex: 100, url: "/PushPDA/Create", closeOnEscape: true, closeAfterAdd: true, afterComplete: function (response) { if (response.responseText) { alert(response.responseText); } } }, { // delete options zIndex: 100, url: "/PushPDA/Delete", closeOnEscape: true, closeAfterDelete: true, recreateForm: true, msg: "Are you sure you want to delete this task?", afterComplete: function (response) { if (response.responseText) { alert(response.responseText); } } }); new_search(); }); //將整數(shù)秒格式轉(zhuǎn)成時(shí)間格式。 function secondToTimeString(seconds) { if (seconds == null) return ""; var hh = parseInt(seconds / 3600).toString(); seconds -= hh * 3600; var mm = Math.round(seconds / 60).toString(); if (hh.length == 1) { hh = "0" + hh; } if (mm.length == 1) { mm = "0" + mm; } return hh + ":" + mm; } //解析JOSN返回的日期字符串格式。 function DatefromJSON(jsonstr) { // return eval (jsonstr.replace(new RegExp('/Date\\((-?[0-9]+)\\)/','g'),'new Date($1)')).toLocalDateString(); if (jsonstr == null) return ""; d = eval('new ' + (jsonstr.replace(/\//g, ''))); var month = (d.getMonth() + 1); month = ("00" + month).substr(("" + month).length); var day = d.getDate() day = ("00" + day).substr(("" + day).length); return d.getFullYear() + "-" + month + "-" + day; }
2、手工構(gòu)建查詢(xún)參數(shù)
(1)單字段搜索:
主要構(gòu)建的查詢(xún)參數(shù)為searchField,searchString,searchOper
var searchPara = { // 構(gòu)建查詢(xún)需要的參數(shù) searchField: "Line", searchString: strLines, searchOper: "in" }; // 獲得當(dāng)前postData選項(xiàng)的值 var postData = $("#grid").jqGrid("getGridParam", "postData"); // 將查詢(xún)參數(shù)融入postData選項(xiàng)對(duì)象 $.extend(postData, searchPara); $("#grid").jqGrid("setGridParam", { url: "/PushPDA/GetTodoLists", search: true //將jqGrid的search選項(xiàng)設(shè)為true }).trigger("reloadGrid", [{ page: 1 }]); // 重新載入Grid表格,以使上述設(shè)置生效
(2)多字段搜索
主要構(gòu)建的查詢(xún)參數(shù)為groupOp,rules,filed,op,data.
var rules = ""; // 構(gòu)建查詢(xún)需要的參數(shù) var searchField = "Line"; var searchString = strLines; var searchOper = "in"; if (searchField && searchOper && searchString) { //如果三者皆有值且長(zhǎng)度大于0,則將查詢(xún)條件加入rules字符串 rules += ',{"field":"' + searchField + '","op":"' + searchOper + '","data":"' + searchString + '"}'; } if (strDate1) { rules += ',{"field":" IP","op":"eq","data":"' + strDate1 + '"}'; } if (rules) { //如果rules不為空,且長(zhǎng)度大于0,則去掉開(kāi)頭的逗號(hào) rules = rules.substring(1); } //串聯(lián)好filtersStr字符串 var filtersStr = '{"groupOp":"AND","rules":[' + rules + ']}'; // 獲得當(dāng)前postData選項(xiàng)的值 var postData = $("#grid").jqGrid("getGridParam", "postData"); // 將查詢(xún)參數(shù)融入postData選項(xiàng)對(duì)象 $.extend(postData, { filters: filtersStr }); $("#grid").jqGrid("setGridParam", { url: "/PushPDA/GetTodoLists", search: true // 將jqGrid的search選項(xiàng)設(shè)為true }).trigger("reloadGrid", [{ page: 1 }]); // (7)重新載入Grid表格,以使上述設(shè)置生效
3、后臺(tái)根據(jù)查詢(xún)條件返回查詢(xún)結(jié)果
注意使用Linq語(yǔ)句,以及動(dòng)態(tài)Linq查詢(xún)。
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. { IQueryable<PushPdaInfo> pdas = db.PushPDAs; IQueryable<PushPdaInfo> todoListsResults = null; //搜索 if (_search) { if (!string.IsNullOrEmpty(searchField))//單字段搜索 { todoListsResults = pdas.Where(p => searchString.IndexOf(p.Line) > -1); } else if (!string.IsNullOrEmpty(filters))//多字段搜索 { JObject ofilters = JObject.Parse(filters); string searchField1; string searchString1; string sql; for (int i = 0; i < ofilters["rules"].Count(); i++) { searchField1 = ofilters["rules"][i]["field"].ToString(); searchString1 = ofilters["rules"][i]["data"].ToString(); sql = "\"" + searchString1 + "\".Contains(" + searchField1 + ")"; todoListsResults = pdas.Where(sql); } } } else { return Json(new { }, JsonRequestBehavior.AllowGet); } //排序 if (string.IsNullOrEmpty(sidx)) sidx = "IP"; todoListsResults = todoListsResults.OrderBy(sidx + " " + sord); //分頁(yè) int pageIndex = Convert.ToInt32(page) - 1; int pageSize = rows; int totalRecords = pdas.Count(); var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows); todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize); var todoListsResults1 = from p in todoListsResults.ToList() select new { p.ID, p.IP, p.Owner, p.Line, p.Status, p.Type, UpdateDate = p.UpdateDate.HasValue ? p.UpdateDate.GetValueOrDefault().ToShortDateString() : "", UpdateTime = p.UpdateTime.HasValue ? IntTimeToStringTime(p.UpdateTime.GetValueOrDefault()) : "" }; var jsonData = new { total = totalPages, page, records = totalRecords, rows = todoListsResults1 }; return Json(jsonData, JsonRequestBehavior.AllowGet); }
4、定義HTML
<div id="search_container" title="Search Options"> <div id="boxbody"> <fieldset> <legend>Query IP<span id="spanClearDates">[Clear]</span></legend> <table> <tr> <td><strong>掃描槍IP: </strong> <input id="Text_Date1" type="text" /> </td> </tr> </table> </fieldset> </div> </div> <div> <table id="grid"></table> <div id="pager"></div> </div>
到此這篇關(guān)于Jquery使用JQgrid組件處理json數(shù)據(jù)的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
jQuery簡(jiǎn)單實(shí)現(xiàn)仿京東商城的左側(cè)菜單效果代碼
這篇文章主要介紹了jQuery簡(jiǎn)單實(shí)現(xiàn)仿京東商城的左側(cè)菜單效果代碼,通過(guò)簡(jiǎn)單的jQuery鼠標(biāo)事件及元素動(dòng)態(tài)變換實(shí)現(xiàn)樣式動(dòng)態(tài)切換功能,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下2015-09-09使用jQuery實(shí)現(xiàn)一個(gè)類(lèi)似GridView的編輯,更新,取消和刪除的功能
在項(xiàng)目中遇到這樣的需求當(dāng)用戶(hù)點(diǎn)擊編輯時(shí),在點(diǎn)擊行下動(dòng)態(tài)產(chǎn)生一行,編輯銨鈕變?yōu)閐isabled,新產(chǎn)生的一行有更新和取消的銨鈕,點(diǎn)擊“取消”銨鈕,刪除剛剛動(dòng)態(tài)產(chǎn)生的行,編輯銨鈕狀態(tài)恢復(fù)。下面小編給大家分享實(shí)例代碼,一起看看吧2017-03-03jquery追加元素的所有方法全面深入實(shí)例講解(append、prepend、after、before、wrap等等)
幾乎所有網(wǎng)站的開(kāi)發(fā)都離不開(kāi)jQuery,jQuery可以很方便的實(shí)現(xiàn)網(wǎng)頁(yè)中的一些效果,也很輕松的對(duì)網(wǎng)頁(yè)中的一些DIV元素進(jìn)行添加,修改或刪除的操作。由于不同位置追加元素的代碼不一樣,本文實(shí)例講解如何對(duì)網(wǎng)頁(yè)中某個(gè)指定的DIV進(jìn)行元素的追加操作。2023-03-03那些年,我還在學(xué)習(xí)jquery 學(xué)習(xí)筆記
那些年學(xué)習(xí)了一些基本的web開(kāi)發(fā)知識(shí),其中已經(jīng)有javascript語(yǔ)言了,為什么還要學(xué)習(xí)Jquery啊2012-03-03jquery提取元素里的純文本不包含span等里的內(nèi)容
如何實(shí)現(xiàn)提取元素里的純文本,不包含span等里的內(nèi)容,這就是本文要為大家介紹的重點(diǎn),你將學(xué)會(huì)使用jquery來(lái)實(shí)現(xiàn)2013-09-09jQuery事件與動(dòng)畫(huà)超詳細(xì)講解
在jquery中,jquery動(dòng)畫(huà)事件和動(dòng)畫(huà)函數(shù)經(jīng)常用的到,今天小編抽時(shí)間給大家整理了些關(guān)于常用的jquery動(dòng)畫(huà)事件和動(dòng)畫(huà)函數(shù),對(duì)jquery動(dòng)畫(huà)函數(shù)和動(dòng)畫(huà)事件相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2022-12-12jquery列表拖動(dòng)排列(由項(xiàng)目提取相當(dāng)好用)
最好的jquery列表拖動(dòng)排列自定義拖動(dòng)層排列。當(dāng)點(diǎn)擊或拖動(dòng)列表時(shí),可以自定義隨意拖放列表模塊到相應(yīng)位置2014-06-06jQuery實(shí)現(xiàn)獲取table中鼠標(biāo)click點(diǎn)擊位置行號(hào)與列號(hào)的方法
這篇文章主要介紹了jQuery實(shí)現(xiàn)獲取table中鼠標(biāo)click點(diǎn)擊位置行號(hào)與列號(hào)的方法,涉及jQuery事件響應(yīng)及針對(duì)table表格元素相關(guān)操作技巧,需要的朋友可以參考下2017-10-10基于jQuery架構(gòu)javascript基礎(chǔ)體系
jQuery畢竟還只是一個(gè)基礎(chǔ)的最底層的工具集,封裝元素選擇器,事件等等,基本上能滿(mǎn)足一般的需求,但要從整體的WEB的周度來(lái)看,為了提高javascript開(kāi)發(fā)的效率與可重用性,就需要有一個(gè)整體的布局2011-01-01