Jquery使用JQgrid組件處理json數(shù)據(jù)
jqGrid 實例中文版網(wǎng)址:http://blog.mn886.net/jqGrid/
國外官網(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軟件開發(fā)公司的Tony Tomov開發(fā)的一個方便人們開發(fā)使用的web組件,它包含了許多免費和開源的庫如:jQuery, ThemeRoller, & jQuery UI等 ,同時最新的版本已經(jīng)支持bootstrapUI,Tony最初的時候是因為他需要一種方式來表示數(shù)據(jù)庫信息,這種方式有速度上的要求同時還要獨立于服務(wù)器端技術(shù)和后臺數(shù)據(jù)庫,于是jqGrid誕生了,從最初的版本到現(xiàn)在已經(jīng)升級到了Guriddo jqGrid 5.4 ,之前的各個版本都是在不斷的修復(fù)bug以及添加符合需求的新功能。jqGrid越來越趨于完善。
jqGrid 是一個用來顯示網(wǎng)格數(shù)據(jù)的jQuery插件,通過使用jqGrid可以輕松實現(xiàn)前端頁面與后臺數(shù)據(jù)的ajax異步通信。

一、jqGrid特性
- 基于jquery UI主題,開發(fā)者可以根據(jù)客戶要求更換不同的主題。
- 兼容目前所有流行的web瀏覽器。
- Ajax分頁,可以控制每頁顯示的記錄數(shù)。
- 支持XML,JSON,數(shù)組形式的數(shù)據(jù)源。
- 提供豐富的選項配置及方法事件接口。
- 支持表格排序,支持拖動列、隱藏列。
- 支持滾動加載數(shù)據(jù)。
- 支持實時編輯保存數(shù)據(jù)內(nèi)容。
- 支持子表格及樹形表格。
- 支持多語言。
- 目前是免費的。
二、調(diào)用ajax的事件順序如下:
- beforeRequest
- loadBeforeSend
- serializeGridData--從第4項開始為返回數(shù)據(jù)過程的事件
- 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, //顯示行號
loadonce:true,//在加載完成后,datatype自動變成local
autowidth: true,
pager: "#pager",
viewrecords: true,//是否顯示總記錄數(shù)
rowNum: 300,//表格中顯示的記錄數(shù)
rowList: [10, 20, 30],
height: '100%',
gridview: true,//整個表格都構(gòu)造完成后再添加到grid中。
jsonReader:{repeatitems:false,id:"2"},//2表示id為rowData的第三個元素。
beforeProcessing:function(res,status,errror){
$.each(res.rows,function(i,n){//在來自Sever的數(shù)據(jù)Grid處理之前,格式化返回的JSON數(shù)據(jù)
n.time=Number(n.time).toExponential(3);
n.shift=["早","中","晚"][n.shift];
});
},
loadComplete:function(xhr){//Grid加載完成后,可對Grid中的元素綁定事件了。分組完成。
$("td.tdQty").bind("click", {}, getDcData);
var rowCount=$(this).getGridParam("records");
},
colModel: [{ name: 'line', index: 'line', width: 80, align: 'center', label: '產(chǎ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: '總點數(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、后臺處理
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時,名稱要與colModel中的名字一致 。
{"total":"10","page":"1","rows"=[{"line":"A1","Shift":3,"qty":123,"time":0.02}],"records":"4"} //records為查詢出的總記錄數(shù),并非本頁記錄數(shù)。2、如果repeatitems:true(默認(rèn))
{"total":"10","page":"1","rows":[{id:"1",cell:["cell1","cell2"]},{id:"2",cell:["cell3","cell4"]}],"records":"4"}對數(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", "錯誤"));
}
$.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: '序列號' },
{ name: 'BoxId', index: 'BoxId', align: 'center', label: '箱號' },
{ name: 'progress_recid', key: true, index: 'progress_recid', width: 80, align: 'center', label: '內(nèi)部號' }/
//key: true主鍵,服務(wù)器返回的數(shù)據(jù)沒有ID時,將此作為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 != "在貨倉") {
$("#tableOEE").setSelection(rowid, false);//取消選擇
alert("在貨倉狀態(tài)的卡板,只能由SIS人員操作");
}
var selRows = $("#tableOEE").getGridParam('selarrrow');//'selrow'最后選擇行的主鍵
if (selRows.length > 2) {
$("#tableOEE").setSelection(rowid, false);
alert("只能選擇兩個序列號更換");
}
}
}六、 JQgrid構(gòu)建查詢

1、定義Jqgrid
ajax遠(yuǎn)端請求分頁,排序,手工構(gòu)建搜索參數(shù),進(jìn)行服務(wù)端查詢,以及CURD操作。
$(function () {
$("#grid").jqGrid({
url: "/PushPDA/GetTodoLists",
datatype: 'json',
mtype: 'Get',
colNames: ['操作', 'ID', 'IP', '所屬人', '生產(chǎn)線', '狀態(tài)', '類型', '更新日期', '更新時間'],
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) {//格式化返回數(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)成時間格式。
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)建查詢參數(shù)
(1)單字段搜索:
主要構(gòu)建的查詢參數(shù)為searchField,searchString,searchOper
var searchPara = { // 構(gòu)建查詢需要的參數(shù)
searchField: "Line",
searchString: strLines,
searchOper: "in"
};
// 獲得當(dāng)前postData選項的值
var postData = $("#grid").jqGrid("getGridParam", "postData");
// 將查詢參數(shù)融入postData選項對象
$.extend(postData, searchPara);
$("#grid").jqGrid("setGridParam", {
url: "/PushPDA/GetTodoLists",
search: true //將jqGrid的search選項設(shè)為true
}).trigger("reloadGrid", [{ page: 1 }]); // 重新載入Grid表格,以使上述設(shè)置生效(2)多字段搜索
主要構(gòu)建的查詢參數(shù)為groupOp,rules,filed,op,data.
var rules = "";
// 構(gòu)建查詢需要的參數(shù)
var searchField = "Line";
var searchString = strLines;
var searchOper = "in";
if (searchField && searchOper && searchString) { //如果三者皆有值且長度大于0,則將查詢條件加入rules字符串
rules += ',{"field":"' + searchField + '","op":"' + searchOper + '","data":"' + searchString + '"}';
}
if (strDate1) {
rules += ',{"field":" IP","op":"eq","data":"' + strDate1 + '"}';
}
if (rules) { //如果rules不為空,且長度大于0,則去掉開頭的逗號
rules = rules.substring(1);
}
//串聯(lián)好filtersStr字符串
var filtersStr = '{"groupOp":"AND","rules":[' + rules + ']}';
// 獲得當(dāng)前postData選項的值
var postData = $("#grid").jqGrid("getGridParam", "postData");
// 將查詢參數(shù)融入postData選項對象
$.extend(postData, { filters: filtersStr });
$("#grid").jqGrid("setGridParam", {
url: "/PushPDA/GetTodoLists",
search: true // 將jqGrid的search選項設(shè)為true
}).trigger("reloadGrid", [{ page: 1 }]); // (7)重新載入Grid表格,以使上述設(shè)置生效3、后臺根據(jù)查詢條件返回查詢結(jié)果
注意使用Linq語句,以及動態(tài)Linq查詢。
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);
//分頁
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ù)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
jQuery 位置函數(shù)offset,innerWidth,innerHeight,outerWidth,outerHei
jQuery的位置函數(shù)(offset(),innerWidth(),innerHeight(),outerWidth(),outerHeight(),scrollTop(),scrollLeft())小應(yīng)用2010-03-03
Jquery實現(xiàn)多個表格的全選復(fù)選框功能方式
這篇文章主要介紹了Jquery實現(xiàn)多個表格的全選復(fù)選框功能方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
jQuery實現(xiàn)鼠標(biāo)經(jīng)過事件的延時處理效果
這篇文章主要為大家詳細(xì)介紹了jQuery實現(xiàn)鼠標(biāo)經(jīng)過事件的延時處理效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2015-10-10
基于daterangepicker日歷插件使用參數(shù)注意的問題
下面小編就為大家?guī)硪黄赿aterangepicker日歷插件使用參數(shù)注意的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
jQuery動態(tài)創(chuàng)建html元素的常用方法匯總
這篇文章主要介紹了jQuery動態(tài)創(chuàng)建html元素的常用方法,包括jQuery追加元素、遍歷數(shù)組以及使用模板等方法,非常具有實用價值,需要的朋友可以參考下2014-09-09

