jqGrid JSON数据源读取器选项配置

  本章介绍jqGrid配置datatype为 json/jsonp/ jsonstring数据类型时,如何设json数据的读取器。

3.6.5 以后的版本返回的json格式字符串需要为标准格式的,怪异模式的会出错。这个问题主要是jQuery造成,jQuery1.4+版本要求json数据为标准的。参考:jQuery dataType指定为json的问题
关于json的更多信息查看这里: HERE and HERE

 

  JSON数据源

  默认jsonReader配置如下

jQuery("#gridid").jqGrid({
//...
   jsonReader : { 
      root: "rows", 
      page: "page", 
      total: "total", 
      records: "records", 
      repeatitems: true, 
      cell: "cell", 
      id: "id",
      userdata: "userdata",
      subgrid: { 
         root:"rows", 
         repeatitems: true, 
         cell:"cell" 
      } 
   },
//...
});

  json数据处理方法和xml作为数据源很类似。定义jsonReader匹配接受的数据什么比较重要呢?如果datatype设置为json,jqGrid希望获取到的json格式如下

{ 
  "total": "xxx", 
  "page": "yyy", 
  "records": "zzz",
  "rows" : [
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "cell":["cell21", "cell22", "cell23"]},
      ...
  ]
}

  示例中使用的标签描述如下

Tag Description
total 总页数
page 当前页
records 总记录数
rows 包含实际json对象数组数据的键名称
id 此行的唯一id键名称
cell 每行数据中数据数组的键名称。

  jsonReader和xmlReader很相似。jsonReader少了配置行元素的定义。下面是jsonReader的配置。

  • root

  定义从哪个键获取数据,如果配置如下

jQuery("#gridid").jqGrid({
//...
   jsonReader : {root:"invdata"},
//...
});

需要如下JSON格式数据
{ 
  "total": "xxx", 
  "page": "yyy", 
  "records": "zzz",
  "invdata" : [
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "cell":["cell21", "cell22", "cell23"]},
      ...
  ]
}
  • page
  • total
  • records

  定义分页需要的信息

jQuery("#gridid").jqGrid({
//...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords"
   },
//...
});

需要如下JSON格式数据

{ 
  "totalpages": "xxx", 
  "currpage": "yyy",
  "totalrecords": "zzz",
  "invdata" : [
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "cell" :["cell21", "cell22", "cell23"]},
      //...
  ]
}
  • cell

定义数据行中的数据从哪个键获取。

jQuery("#gridid").jqGrid({
//...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "invrow"
   },
//...
});

需要如下JSON格式数据

{ 
  "totalpages": "xxx", 
  "currpage": "yyy",
  "totalrecords": "zzz",
  "invdata" : [
    {"id" :"1", "invrow" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "invrow" :["cell21", "cell22", "cell23"]},
      ...
  ]
}
  • id

定义数据行的唯一id

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "invrow",
      id: "invid"
   },
...
});

需要如下JSON格式数据

{ 
  "totalpages": "xxx", 
  "currpage": "yyy",
  "totalrecords": "zzz",
  "invdata" : [
    {"invid" :"1", "invrow" :["cell11", "cell12", "cell13"]},
    {"invid" :"2", "invrow" :["cell21", "cell22", "cell23"]},
      ...
  ]
}

可以配置cell为空,也可以设置id为数字【此时数据root指向的行为数组对象,id指定数组中列下标对应的项作为唯一id。】

jQuery("#gridid").jqGrid({
...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      cell: "",
      id: "0"
   },
...
});

在这个配置下行数据的第一元素作为id

{ 
  "totalpages" : "xxx", 
  "currpage" : "yyy",
  "totalrecords" : "zzz",
  "invdata" : [
    ["1", "cell11", "cell12", "cell13"],
    ["2", "cell21", "cell22", "cell23"],
      ...
  ]
}
  • repeatitems

告诉jqGrid行数据信息是重复的。例如,返回的数据中定义行元素内容为数组对象。当设置为false,jqGrid获取通过name查找元素,name为colModel中配置的name,或者colModel中配置的jsonmap。

jQuery("#gridid").jqGrid({
//...
   jsonReader : {
      root:"invdata",
      page: "currpage",
      total: "totalpages",
      records: "totalrecords",
      repeatitems: false,
      id: "0"
   },
//...
});

需要如下JSON格式数据

{ 
  "totalpages" : "xxx", 
  "currpage" : "yyy",
  "totalrecords" : "zzz",
  "invdata" : [
    {"invid" : "1","invdate":"cell11", "amount" :"cell12", "tax" :"cell13", "total" :"1234", "note" :"somenote"},
    {"invid" : "2","invdate":"cell21", "amount" :"cell22", "tax" :"cell23", "total" :"2345", "note" :"some note"},
      ...
  ]
}

id元素为invid键。

  这个是一个有用的特性(repeatitems:false),数据源中就不需包含所有colModel中配置中指定的数据。 但我们通过name查询时,顺序就就不需要和colModel的一致。下面的内容也可以被jqGrid正确解析。

{ 
  "totalpages" : "xxx", 
  "currpage" : "yyy",
  "totalrecords" : "zzz",
  "invdata" : [
    {"invid" :"1", "invdate" : "cell11", "note" :"somenote"},
    {"invid" :"2", "amount" : "cell22", "tax" :"cell23", "total" :"2345"},
   //   ...
  ]
}

JSON字符串数据源

  datatype设置为jsonstring和json时拥有相同的特性。唯一不同数据需要的是有效格式的json字符串数据源,可以通过datastr来配置。可以参考datatype设置xmlstring作为示例。

  如果你使用jsonstring作为datatype配置,那么当数据被处理完毕后datatype将自动设置为local,分页将不会起效果。

JSON点符号

  当使用json键值对数据(例如 repeatitems设置为false),可以使用点符号和索引符号。

  colModel定义如下

jQuery("#gridid").jqGrid({
//...
 colModel:[
   {name:'name',label:'Name', width:150,editable: true},
   {name:'id',width:50, sorttype:"int", editable: true,formatter:strongFmatter},
   {name:'email',label:'Email', width:150,editable: true,formatter:'email'},
   {name:'stock',label:'Stock', width:60, align:"center", editable: true,formatter:'checkbox',edittype:"checkbox"},
   {name:'item.price',label:'Price', width:100, align:"right", editable: true,formatter:'currency'},
   {name:'item.weight',label:'Weight',width:60, align:"right", editable: true,formatter:'number'},
   {name:'ship',label:'Ship Via',width:90, editable: true,formatter:'select', edittype:"select",editoptions: value:"2:FedEx;1:InTime;3:TNT;4:ARK;5:ARAMEX"}},      
   {name:'note',label:'Notes', width:100, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"20"}}      
 ],
//...
});

注意name:'item.price' 和 name:'item.weight'定义的元素

上面的colModel需要如下格式数据

{
   "page":"1",
   "total":2,
   "records":"13", 
   "rows":[ 
      {"id":"12345","name":"Desktop Computers","email":"josh@josh.com","item":{"price":"1000.72", "weight": "1.22" }, "note": "note", "stock": "0","ship": "1"}, 
      {"id":"23456","name":"<var>laptop</var>","note":"Long text ","stock":"yes","item":{"price":"56.72", "weight":"1.22"},"ship": "2"},
      {"id":"34567","name":"LCD Monitor","note":"note3","stock":"true","item":{"price":"99999.72", "weight":"1.22"},"ship":"3"},
      {"id":"45678","name":"Speakers","note":"note","stock":"false","ship":"4"} 
    ] 
}

jsonReader使用函数作为配置

  一些情况下你需要从wevservice获取数据,这样就无法配置所有响应数据的属性使jqGrid正常运行。在3.6.4版本之后可以为jsonReader配置为函数,下面为一个示例

jsonReader: {
    repeatitems: false,
    id: "Id",
    root: function (obj) { return obj; },
    page: function (obj) { return 1; },
    total: function (obj) { return 1; },
    records: function (obj) { return obj.length; }
}

obj参数为服务器响应(ajax请求对象)

数组数据

  尽管jqGrid的主要目的是显示从数据库获取的动态数据,jqGrid也有很多方法可以处理客户端的Array数据。

  相关jqGrid配置:datatype
  相关colModel配置:sorttype,datafmt
  相关方法: getRowData, delRowData, setRowData, addRowData, updateGridRows See Methods

  3.7+版本引进了2个新参数datalocalReader。data参数介绍参考:jqGrid选项配置。localReader 和jsonReader拥有如上所述的相同的配置,但是需要的数据时存储在本地的。

  localReader的初始化配置和jsonReader一样。

localReader = {
   root: "rows",
   page: "page",
   total: "total",
   records: "records",
   repeatitems: false,
   cell: "cell",
   id: "id",
   userdata: "userdata",
   subgrid: {root:"rows", repeatitems: true, cell:"cell"}
}

  对jsonReader有效的操作都可以作用于localReader。

If we have defined a pager for grid with client side data, the buttons in pager are automatically disabled. In other words, the current release of grid does not support client side paging and serching.(当定义了一个分页,使用客户端的数据,分页按钮将会自动禁用。就是说,当前发布的jqGrid版本不支持客户端数据的分页和查找。)

  首先我们需要告诉jqGrid需要显示数据的数据再客户端,可以配置datatype,如下所示

jQuery("#grid_id").jqGrid({
//...
   datatype: "clientSide",
//...
});

也可以配置为“local”,和上面的结果一样。


  有了这个就很好为列配置配需类型。如果sorttype没有配置默认为“text”,让我们看下示例中的数组数据

...
<script>
jQuery(document).ready(function(){ 
    jQuery("#list").jqGrid({
        datatype: 'clientSide',
        colNames:['Inv No','Date', 'Amount','Tax','Total','Notes'],
        colModel :[ 
        {name:'invid',index:'invid', width:55, sorttype:'int'}, 
        {name:'invdate',index:'invdate', width:90, sorttype:'date', datefmt:'Y-m-d'}, 
        {name:'amount',index:'amount', width:80, align:'right',sorttype:'float'}, 
        {name:'tax',index:'tax', width:80, align:'right',sorttype:'float'}, 
        {name:'total',index:'total', width:80,align:'right',sorttype:'float'}, 
        {name:'note',index:'note', width:150, sortable:false} ],
        pager: '#pager',
        rowNum:10,
        viewrecords: true,
        caption: 'My first grid'
   }); 
//...
}); 
</script>

示例中使用了新配置: datatype, sortype和 datefmt.


sorttype可用值有

  1. int - 数据按照整形来处理
  2. float -数据按照浮点数来处理
  3. date - 数据按照日期格式来处理
  4. text - 数据按照文本格式 来处理

  我们需要为这些信息选择合适的排序类型。sorttype为date时需要知道呈现在grid中的日期格式。默认格式为ISO格式: 'Y-m-d'。日期格式和php一样。获取更多信息,清参阅php.net。

  添加数据,可以使用addRowData.方法,参数如下

jQuery("#grid_id").addRowData( rowid, data, position, srcrowid );

其中

  • rowid:这个值将作为行的id
  • data:和colModel中定义的name一样,json键值对对象
  • position:指定数据添加的位置,可以为first, last, before 或者after
    1)“first” 在grid顶部添加一行数据【默认值】
    2) “last” 再grid最后天际爱一行数据
    3)“before” 和 “after” 依据srcrowid.配置的值
  • srcrowid:使用“before” 或者 “after”插入新数据到grid中需要参考的某行id值
//...
var myfirstrow = {invid:"1", invdate:"2007-10-01", note:"note", amount:"200.00", tax:"10.00", total:"210.00"};
jQuery("#list").addRowData("1", myfirstrow);
//...

使用上面的代码将会插入数据行到第一,注意键值对出现顺序是任意的。也可以设置单独的键值对,如下

//...
jQuery("#list").addRowData("2", {amount:"300.00"});
//...

此示例中我们加入了只包含金额一行数据。

使用getRowData方法获取数据

jQuery("#grid_id").getRowData( rowid );

参数 rowid为需要获取的行的id。

jQuery("#list").getRowData( "1" );

如上代码将获取json键值对结果,结果如下所示

{invid:"1", invdate:"2007-10-01", note:"note", amount:"200.00", tax:"10.00", total:"210.00"};

使用delRowData方法删除行

jQuery("#grid_id").delRowData( rowid );

参数 rowid为需要删除的行的id。

jQuery("#list").delRowData( "2" );

上面代码将会删除id为2的行

这个方法成功删除时返回true,否则false。

 

要修改某行的数据,可以使用setRowData方法。

jQuery("#grid_id").setRowData( rowid, data );

rowid为需要修改的行的id
data 是新数据。json键值对对象

jQuery("#list").setRowData( "1", { tax:"5", total:"205" });

上面代码将修改id为1行的tax和total的值。方法成功更新返回true,否则false。

要一次性修改多行数据可以使用updateGridRows方法,详细参阅: Addon methods

来源:http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data

加支付宝好友偷能量挖...


原创文章,转载请注明出处:jqGrid JSON数据源读取器选项配置

评论(0)Web开发网
阅读(3628)喜欢(1)jqGrid中文API