【问题标题】:JQuery JQGrid: How to load JSON data from Spring MVC 3 @RequestBodyJQuery JQGrid:如何从 Spring MVC 3 @RequestBody 加载 JSON 数据
【发布时间】:2010-11-18 03:03:02
【问题描述】:

我真的不想问这个问题,因为我认为这应该像数 1-2-3 一样简单。从昨天到今天我都在研究,但没有找到解决办法。

这就是我想要做的。从我的 Spring MVC 3 控制器中检索 JSON 数据并将该数据显示在我的 JQGrid 上。

为了设置我的控制器来发送 JSON 数据,我遵循了这篇文章 Ajax Simplifications in Spring 3.0 中的建议

这是处理 JSON 请求的请求映射:

@RequestMapping(value = "/users", method = RequestMethod.GET)
public @ResponseBody  List<UserDTO>viewUsersAsJSON(HttpServletRequest request, HttpServletResponse response, ModelMap model) {

    logger.debug("Retrieving all users as JSON");

    return userRoleService.getAll();
}

此映射有效,因为我能够从 Firefox 和 RESTClient 检索 JSON 数据。这是示例 JSON 数据输出(我必须删除敏感数据):

[{"username":"johnsmith","userId":1,"firstName":"John","lastName":"Smith","id":"1"},{"username":"stackoverflow","userId":2,"firstName":"Stack","lastName":"Overflow","id":"2"}]

我无需在 Firefox 或 RESTClient 中指定任何 Accept=application/json 标头即可获取此数据。我只需输入完整的 URL 即:http://localhost/myapp/users

我没有对我的 Spring MVC 3 映射进行任何特殊配置或 XML 配置,因为我希望(根据文章和我得到的结果)它可以正常工作并给我 JSON。

这是我在 JSP 页面上声明的 JqGrid:

Javascript:

 <script type="text/javascript">
 jq(function() {
  jq("#list2").jqGrid({
      url:'/myapp/users',
   datatype: 'json',
   mtype: 'GET',
      colNames:['Id','Username', 'User Id', 'First Name', 'Last Name'],
      colModel:[
       {name:'id',index:'id', width:55},
       {name:'username',index:'username', width:90},
       {name:'userId',index:'userId', width:90},
       {name:'firstName',index:'firstName', width:100},
       {name:'lastName',index:'lastName', width:80, align:"right"}
      ],
      rowNum:10,
      rowList:[10,20,30],
      pager: '#pager2',
      sortname: 'id',
      viewrecords: true,
      sortorder: "desc",
      caption:"Users Table"
  });
  jq("#list2").jqGrid('navGrid','#pager2',{edit:false,add:false,del:false});

 });


</script>

这是我在 JSP 中声明的 CSS 元素:

<table id="list2"></table>
<div id="pager2"></div>

我运行了 Firefox 错误控制台。未发现错误。我跑了萤火虫。我也没有看到任何错误。

JqGrid 加载了正确的列名,但它是空的!我使用简单的数组数据在不同的 JSP 页面上设置了另一个 JqGrid,它能够加载数据。有什么想法或解决方案吗?

很难找到 Spring MVC 3 JSON JqGrid 集成的任何工作示例。

【问题讨论】:

    标签: jquery json spring jqgrid request


    【解决方案1】:

    要让 jqGrid 接受 JSON,您需要定义一个 jsonreader (details here) 或设置输出以使其符合 jqgrid 期望的默认值。如果你没有完全按照预期构建它,jqGrid 将会默默地失败。

    要使用默认的 jsonreader,您需要重新构建 JSON,使对象如下所示:

    {"page":1,"total":1,"records":1,"rows":[{"id":1,"cell":["johnsmith",1,"John","Smith",1]}]}
    

    【讨论】:

    • 感谢您的快速回复。我现在要读那个链接。希望它有我正在寻找的东西:)
    • 没问题。我刚刚更新了一个示例,说明如何使用默认的 jsonreader 进行操作;希望这能让您顺利完成剩下的工作。
    • 我现在看到了。 JqG​​rid 需要一个精确的 JSON 格式(您可以通过 jsonReader 指定如何映射它)。我想这就是我现在需要的。
    • 问题已解决。我只是通过遵循 jsonReader 来让它工作(虽然我有另一个问题,但这与这个无关)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    相关资源
    最近更新 更多