首页 > 代码库 > 前后台JSON交互

前后台JSON交互

基础环境 spring+mybatis

技术分享
        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(‘服务器请求超时!‘);
                 },

               });
        }
前台
技术分享
    @RequestMapping(value="http://www.mamicode.com/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();
        }
    }
controller

 

前后台JSON交互