Spring MVC前端JSON数据传到后端
传送List json
前端发送数据代码:
//准备数据 var componetsArray = new Array(); var dataTmp = {}; dataTmp["component_id"] = panel_biee_components.attr("id"); dataTmp["component_width"] = orgNumIndex; componetsArray.push(JSON.stringify(dataTmp)); //发送请求 $.ajax({ type: "POST", url: $("#porjectPath").val()+"/f/report/rdss2Report/saveReport", datatype: "json", data:{"listParam" : componetsArray}, success: function(data) { alert(data.result); } });
后端接收参数代码
@RequestMapping(value="/saveReport", method=RequestMethod.POST) @ResponseBody public void saveReport(HttpServletRequest request, HttpServletResponse response, @RequestParam("listParam[]") List<String> param) { JSONObject jo = new JSONObject(); try { System.out.println(param); jo.put("result", "success"); PrintWriter out = null; response.setContentType("application/json"); out = response.getWriter(); out.write(jo.toString()); } catch (Exception e) { jo.put("result", "fail"); PrintWriter out = null; response.setContentType("application/json"); try { out = response.getWriter(); } catch (IOException e1) { e1.printStackTrace(); } out.write(jo.toString()); e.printStackTrace(); } }
传送Map json复杂数据:
前端发送数据代码:
var componetsArray = new Array(); var dataTmp = {}; dataTmp["component_id"] = panel_biee_components.attr("id"); dataTmp["component_width"] = orgNumIndex; componetsArray.push(JSON.stringify(dataTmp)); var jsonStr = JSON.stringify(componetsArray); var jsonObject = {}; jsonObject['title']="标题"; jsonObject['par']=jsonStr; $.ajax({ type: "POST", url: $("#porjectPath").val()+"/f/report/rdss2Report/saveReport", datatype: "json", data:jsonObject, success: function(data) { alert(data.result); } });
后端接收参数代码
@RequestMapping(value="/saveReport", method=RequestMethod.POST) @ResponseBody public void saveReport(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> param) { JSONObject jo = new JSONObject(); try { System.out.println(param); JSONArray ja = JSONArray.fromObject(param.get("par").toString()); System.out.println(ja.toString()); jo.put("result", "success"); PrintWriter out = null; response.setContentType("application/json"); out = response.getWriter(); out.write(jo.toString()); } catch (Exception e) { jo.put("result", "fail"); PrintWriter out = null; response.setContentType("application/json"); try { out = response.getWriter(); } catch (IOException e1) { e1.printStackTrace(); } out.write(jo.toString()); e.printStackTrace(); } }
抱歉,暂停评论。