我正在使用jqGrid 3.6.4和jquery 1.4.2。在我的样本中,我正在遵循json数据格式&我想将这些json数据映射到jqgrid的行
{
"page": "1",
"total": 1,
"records": "6",
"rows": [
{
"head": {
"student_name": "Mr S. Jack ",
"year": 2007
},
"sub": [
{
"course_description": "Math ",
"date": "22-04-2010",
"number": 1,
"time_of_add": "2:00",
"day": "today"
}
]
}
]
}
我的jqgrid代码如下
jQuery("#"+subgrid_table_id).jqGrid({
url:"http://localhost/stud/beta/web/GetStud.php?sid="+sid,
dtatype: "json",
colNames: ['Stud Name','Year','Date'.'Number'],
colModel: [ {name:'Stud Name',index:'student_name', width:100, jsonmap:"student_name"},
{name:'Year',index:'year', width:100, jsonmap:"year"},
{name:'Date',index:'date', width:100, jsonmap:"date"},
{name:'Number',index:'number', width:100, jsonmap:"number"}
],
height:'100%',
jsonReader: { repeatitems : false, root:"head" },
});
所以现在问题是我的数据,即student_name和year在“head”下,jqgrid可以找到这两个字段。同时其他两个列值,即日期和数字位于“sub”下,甚至那些列我无法用jqgrid映射
请帮助我如何在JQGrid中找到这些属性。
由于
答案 0 :(得分:15)
首先发布的代码有一些错误,例如dtatype: "json"
而不是datatype: "json"
。代码末尾的“},});
”代替“}});
”而colNames: ['Stud Name','Year','Date'.'Number']
代替colNames: ['Stud Name','Year','Date','Number']
。修复此明确的错误后,您需要更改jsonmap
值。这是你的主要问题。固定代码如下所示:
jQuery("#"+subgrid_table_id).jqGrid({
...
datatype: 'json',
colNames: ['Stud Name','Year','Date'.'Number'],
colModel: [
{name:'student_name', width:100, jsonmap:"head.student_name"},
{name:'year', width:100, jsonmap:"head.year"},
{name:'date', width:100, jsonmap:"sub.0.date"},
{name:'number', width:100, jsonmap:"sub.0.number"}
],
jsonReader: { repeatitems:false, root:"rows" }
});
您必须将root
修改为“rows
”并在 JSON点符号中使用jsonmap
(请参阅http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_dot_notation)。我使用了一些奇怪的符号,例如“sub.0.number
”,因为JavaScript中的sub.0.number
与sub[0].number
相同。它现在有效。
我建议您再考虑一下您收到的JSON数据的结构。 (请参阅我之前对你的评论问题):“sub”元素是否真的是一个总是有一个元素的数组,或者你想使用subgrids?可能数据应该从sub:[{"":"", ...}]
更改为sub:{"":"", ...}
?你想用什么作为rowid? student_name
?然后将id: "head.student_name"
添加到jsonReader
定义,或将key: true
属性添加到列student_name
的定义中。或者您忘记将其包含在JSON数据中?
最后一个建议。如果您打开http://trirand.com/blog/jqgrid/jqgrid.html并在树的左侧打开分支“数据映射”\“数据优化”,您将看到一个示例,其中仅使用数组而不是JSON中的命名元素。这些数据的大小最小,可以更快地从服务器传输到客户端。您的数据改为包含一些您根本不使用的字段(例如“ course_description ”)。所以如果您可以对服务器进行任何更改代码,请尝试优化数据传输速率。