2010-11-18 93 views
1

我真的很難問這個,因爲我認爲這應該和計數1-2-3一樣簡單。自昨天和今天以來我一直在研究,但我找不到解決方案。JQuery JQGrid:如何從Spring MVC 3加載JSON數據@RequestBody

這是我想要做的。從我的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實現=應用程序/ JSON頭得到這個數據。我只是鍵入完整的URL即:http://localhost/myapp/users

我沒有做任何特殊配置或XML配置在我的Spring MVC 3映射,因爲我期望(基於文章和我得到的結果),它只是工作,並給我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> 

這裏是我的CSS元素作爲JSP聲明:

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

我跑的Firefox錯誤控制檯。找不到錯誤。我跑了Firebug。我也沒有看到任何錯誤。

JqGrid加載正確的列名稱,但它是空的!我使用簡單的數組數據在另一個JSP頁面上安裝另一個JqGrid,並且它能夠加載數據。任何想法或解決方案?

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

回答

2

要讓jqGrid接受您需要定義jsonreader(details here)或設置輸出以使其符合jqgrid預期的默認值的JSON。如果你沒有完全按照預期構建它,jqGrid會默默地失敗。

爲了與jsonreader你要調整你的JSON使物體看起來像這樣的默認這項工作:

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

感謝您的快速反應。我現在要讀那個鏈接。希望它有我在找什麼:) – chris 2010-11-18 03:13:07

+0

沒問題。我剛剛更新了一個如何使用默認jsonreader的例子;希望這會讓你在那裏休息。 – 2010-11-18 03:25:44

+0

我現在看到它。 JqG​​rid期待一個確切的JSON格式(您可以指定如何通過jsonReader映射它)。我認爲這是我現在需要的。 – chris 2010-11-18 03:29:44