我有一个JSON
{"empId":"4444","skill":{"rating":"1","review":"Great"},"productivity":{"rating":"2","review":"Good"}};
这是我到目前为止的jqgrid代码的colModel。
colModel: [
{name:'skill.rating',label:'Skill Rating', width:150,editable: true},
{name:'skill.review',label:'Skill Review', width:150,editable: true},
{name:'productivity.rating',label:'Productivity Rating',width:150,editable: true},
{name:'productivity.review',label:'Productivity Review', width:150,editable: true}]
但是,如果有新类别的Reliability Review and Rating,那么这种网格设计将使以后的扩展变得困难,因此必须手动更改网格设计。
相反,我想使它在网格中以这种格式显示
Category || Rating || Review
----------------------------------
Skill || 1 || Great
Productivity || 2 || Good
Reliability || 3 || Average
是否可以使用Jqgrid做到这一点,而不必更改JSON对象的结构(因为我无法控制该对象,因此只能通过服务来获取它)? < / p>
答案 0 :(得分:1)
最好操作jsonReader(可以是一个函数),而不要更改colModel。有关详细说明,请参见Guriddo docs
尝试以下代码:
colModel: [
{name:'category',label:'Category', width:150,editable: true},
{name:'rating',label:'Skill Rating', width:150,editable: true},
{name:'review',label:'Skill Review', width:150,editable: true}
],
jsonReader : {
root : function (data) {
var ret = [];
for( var key in data) {
if($.isPlainObject(data[key])) {
var tmp = data[key];
tmp.category = key;
ret.push(tmp);
}
}
return ret;
}
},
更新
工作代码下方
HTML
<table id="jqGrid"></table>
<div id="jqGridPager"></div>
JavaScript
var mydata ={"empId" : "4444", "skill" : "rating":"1", "review":"Great"}, "productivity" : {"rating":"2","review":"Good"}, "reliability" : {"rating":"3","review":"Very Good"}};
$("#jqGrid").jqGrid({
datastr : mydata,
datatype: "jsonstring",
colModel: [
{name:'category',label:'Category', width:150,editable: true},
{name:'rating',label:'Skill Rating', width:150,editable: true},
{name:'review',label:'Skill Review', width:150,editable: true}
],
jsonReader : {
root : function (data) {
var ret = [];
for( var key in data) {
if($.isPlainObject(data[key])) {
var tmp = data[key];
tmp.category = key;
ret.push(tmp);
}
}
return ret;
}
},
viewrecords: true,
width: 780,
rowNum: 15,
//cellEdit : true,
rownumbers: true, // show row numbers
rownumWidth: 25, // the width of the row numbers columns
pager: "#jqGridPager"
});
此处指向jsfiddle example的链接 数据类型为jsonstring,但与json相同。该集合主要供jsfiddle使用。