在jqGrid中加载JSON数据

时间:2012-03-27 17:33:24

标签: jqgrid jsonreader

在jqGrid中显示我的json数据时遇到了麻烦。

我在这个论坛上搜索了很多,并尝试了各种形式来使其发挥作用。如果这已经得到回答,我很抱歉,但我真的需要帮助。

在服务器页面,我只使用 JavaScriptSerializer 发送数据,使用默认参数 jsonreader 函数(这个工作正常)。

我现在需要分页并更改我的服务器页面代码以使用 sidx sord 参数。

来自服务器的结果字符串如下所示:

{"total":"344","page":"1","records":"8577","root":[{"Id":"1","SerialNumber":"132","Name":"ServerName"},...]}

这是我的jQuery代码:

$("#list").jqGrid({
        datatype: "json",
        mtype: 'GET',
        url:'https://server/handlerpage.ashx',
        colNames:['Id','SerialNumber','Name'],
        colModel :[         
                {name:'Id', index:'Id', jsonmap:"Id", width:20},
                {name:'Name', index:'Name', jsonmap:"Name", width:120},
                {name:'SerialNumber', index:'SerialNumber', jsonmap:"SerialNumber", width:100}],    
        jsonreader: {repeatitems:false,id:'Id',root:'root'},
        pager: '#pager',
        rowNum:25,
        rowList:[25,50,75,100],
        sortname: 'Id',
        viewrecords:true,
        gridview: true,
        height:"400",
        width:"700",
        caption: 'Select from existing server',
        loadtext:'Loading, please wait'
      }).navGrid("#pager", { edit: false, add: false, search: true, del: false });

3 个答案:

答案 0 :(得分:3)

为了使用json数据作为查询的响应,必须正确格式化响应。很难确定什么是正确的响应以及如何从文档中获取它。由于您的服务器设置会在响应中生成警告而导致网格无法加载,因此可能会出现更多问题。

从文档中这是默认的json阅读器,这意味着如果您正确格式化您的响应,则无需添加任何内容/自定义json阅读器。

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

首先确保您拥有正确的响应格式。 {"page":1,"total":1,"records":"2","rows":[{"id":"1","cell":["1","mydata1"]},{"id":"2","cell":["2","mydata2"]}]}

在文档页面上没有给出样本,但如果您的网格中只有两列,则上述内容是正确的。您需要让服务器查询/解析服务器查询,并将值传递给运行服务器端脚本的页面以返回此格式。文档中的example.php页面为您提供了所需的所有值。

此代码将为您提供正确的标头,以避免错误警告并与上面的响应相匹配。另请注意,在文档中,它们不会在关联数组索引名称的索引周围添加撇号。那会失败。

header('Content-type: application/json');$responce = new stdClass();$responce->page = $page;$responce->total = $total_pages;$responce->records = $count;$i=0;while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {$responce->rows[$i]['id']=$row['ID'];$responce->rows[$i]['cell']=array($row['ID'],$row['entity_name']); $i++; } echo json_encode($responce);

重新记录文档中缺少的内容(有可能我错过了它们,即使jQgrid的文档是史诗/大师的工作): 1.没有提到需要json的头语句(XML示例很清楚) 2.没有工作返回字符串的样本 3.缺少关联数组索引的正确格式。 4.没有提到如何避免作为响应的一部分返回PHP警告

答案 1 :(得分:1)

尝试以下

jsonReader: {
    root: 'rows',
    page: 'page',
    total: 'total',
    records: 'records',
    repeatitems: true,
    cell: 'cell',
    id: 'id',
    userdata: 'userdata'
}

答案 2 :(得分:0)

请确保服务器端脚本正在返回带有HEADERS

的正确json字符串

进一步检查demo网站和JSON示例