前后台JSON交互
基础环境 spring+mybatis
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
function postUser(){ var userName=$("input[name='userName']").val(); var age=$("input[name='age']").val(); var model=new Object(); model.userName=userName; model.age=age; $.ajax({ type : 'post', url : '<%=basePath%>user/postUser', //设置contentType类型为json contentType : 'application/json;charset=utf-8', //json数据 data : JSON.stringify(model), //请求成功后的回调函数 success : function(data) { alert(data.result); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert('服务器请求超时!'); }, }); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@RequestMapping(value="/postUser",method=RequestMethod.POST) public void postUser(@RequestBody String objJson,HttpServletRequest request,HttpServletResponse response){ System.out.println("postUser"); String result = "{\"result\":\"success\"}"; try { System.out.println(objJson); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.write(result); } catch (Exception e) { e.printStackTrace(); } }