Ajax和SpringMVC之間JSON交互

Ajax和SpringMVC之間的json數據傳輸有兩種方式:javascript

1.直接傳輸Json對象前端

2.將Json序列化java

 

1.直接傳輸Json對象ajax

前端Ajaxjson

$(document).ready(function(){
    $("#btn_login").click(function(){
        var dataJson = {
            username:$("#username").val(),
            password:$("#password").val()
        };
        $.ajax({
            url:"/login/",
            type:"post",
            data:dataJson,
            contentType:"application/x-www-form-urlencoded",//如不設置此項,默認也爲此,設置發送給後端的類型
            dataType:"json",//設置接收後端的數據的類型
            async:true,//設置異步,否則可能接收不到後端返回的json
            success:function(data){//data爲後端返回的json
                if(data.code==0){
                    window.location.reload();
                }
                else {

                }
            }
        });
    });
});

後端使用後端

@RequestMapping(path = {"/login/"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletResponse response) {
        try {
            Map<String, Object> map = userService.login(username, password);
            if (map.containsKey("ticket")) {
                Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
                cookie.setPath("/");
                response.addCookie(cookie);
                //return "redirect:/";
              return CommonUtil.getJSONString(0, "成功");
            } else {
                //return "redirect:/";
                return CommonUtil.getJSONString(1, map);
            }

        } catch (Exception e) {
            logger.error("登陸異常" + e.getMessage());
            //return "redirect:/";
            return CommonUtil.getJSONString(1, "註冊異常");
        }
    }

使用@RequestParam,即便用Servlet的request.getgetParameter。這種方式能夠接受以application/x-www-form-urlencoded這種方式傳輸的JSON對象的。 cookie

2.將Json序列化app

Ajax異步

$(document).ready(function(){
    $("#btn_reg").click(function(){
        var dataJson = {
            username:$("#regusername").val(),
            password:$("#regpassword").val()
        };
        $.ajax({
            url:"/reg/",
            type:"post",
            contentType:"application/json",//以json字符串形式傳輸
            data:JSON.stringify(dataJson),//將json對象序列化成字符串
            dataType:"json",
            async:true,
            success:function(data){
                if(data.code==0){
                    window.location.reload();
                }
                else {

                }
            }
        });

    });
});

後端async

@RequestMapping(path = {"/reg/"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String reg(@RequestBody User user,
                      HttpServletResponse response) {
        try {
            Map<String, Object> map = userService.register(user.getUsername(), user.getPassword());
            if (map.containsKey("ticket")) {
                Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
                cookie.setPath("/");

                response.addCookie(cookie);
                return CommonUtil.getJSONString(0, "註冊成功");
            } else {
                return CommonUtil.getJSONString(1, map);
            }

        } catch (Exception e) {
            logger.error("註冊異常" + e.getMessage());
            return CommonUtil.getJSONString(1, "註冊異常");
        }
    }

@RequestBody中的user中,必須有與前端名稱一致的屬性,才能夠接受到相應數據。

處理以外,@RequestBody還可用Map<String,Object> map來接收。

 

參考:https://blog.csdn.net/LostSh/article/details/68923874

相關文章
相關標籤/搜索