首页 > 代码库 > jQuery ajax 传递JSON数组到Spring Controller

jQuery ajax 传递JSON数组到Spring Controller

     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