標籤:arrays hashmap size 擷取 cts datagrid man job files
jQuery ajax傳遞單個JSON對象到後台很容易,這裡記錄的是傳遞多個JSON對象組成的JSON數組到java 後台,並說明java如何解析JSON數組。
1、js代碼
var relationArrays=new Array();
//擷取所有組的人員資訊grid資料
var allGrid= $(".userGrid");
for(var i=0;i<allGrid.length;i++){
var rows=$(allGrid[i]).datagrid("getRows");
$.each(rows,function(i,item){
relationArrays.push(item);
})
}
$.ajax({
type : "POST",
url : ‘../projectController/addRelations‘,
data:{"params":JSON.stringify(relationArrays)},
dataType : ‘json‘,
cache : false,
success : function(data) {
alert(data.msg);
}
});
2、java代碼
@RequestMapping("/addRelations")
public void addRelations(HttpServletRequest request,HttpServletResponse response, HttpSession session) {
String jsonStr = request.getParameter("params");
//儲存需要insert的項目個人關係資訊
List<ProjectRelation> relationList=new ArrayList<ProjectRelation>();
ProjectRelation relation=null;
JSONArray jsonArray = JsonUtil.parseArray(jsonStr);
for(Object ob : jsonArray){
JSONObject jObject = (JSONObject) ob;
relation=new ProjectRelation();
relation.setProjectId(pId);
relation.setChargemanId(jObject.getInteger("chargemanId"));
relation.setGroupId(jObject.getInteger("groupId"));
relation.setUserId(jObject.getInteger("userId"));
relation.setProjectRole(jObject.getInteger("projectRole"));
relationList.add(relation);
}
//先查詢項目中所有已有人員資訊,
int result=projectServiceImpl.saveProjectRelations(relationList);
HashMap<String, Object> map = new HashMap<String, Object>();
try {
if(result==jsonArray.size()){
map.put("msg", "關聯資訊添加成功");
}
else {
map.put("msg", "關聯資訊添加錯誤");
}
WriteJsonUtil.writejson(map, response);
} catch (Exception e) {
e.printStackTrace();
map.put("msg", "關聯資訊添加錯誤");
WriteJsonUtil.writejson(map, response);
}
}
3、JSONUtil代碼
public static JSONArray parseArray(String text){
JSONArray jsonArray=JSON.parseArray(text);
return jsonArray;
}
具體JsonUtil代碼請從該連結下載http://files.cnblogs.com/files/DylanZ/JsonUtil.rar
jQuery ajax 傳遞JSON數組到Spring Controller