1. 程式人生 > >AJax提交表單資料到後臺springmvc接收

AJax提交表單資料到後臺springmvc接收

第一種方法直接用serialize()方法
function insert(){
        $.ajax({
            type:"POST",
            url:"${pageContext.request.contextPath}/order/insert",
            data : $("#fom").serialize(),             
            success  :function (res) {
                console.log(res); 
            error:function () {                
            }
        });
}

後臺springmvc用物件引數接收 可以自動轉換為物件,需要注意的就是form表單中的name要和物件中的引數名相同

@RequestMapping(value = "/insert",method = RequestMethod.POST)
        public String insert( Order order){
           int result=this.orderSerivce.insert(order);
           if(result==1){
               System.out.println("新增失敗");
               return "101";
           }
           return "100";
        }


第二種是用JSON.stringify()將json物件轉化為json物件的字串傳遞
function insert(){
        $.ajax({
            type:"POST",
            url:"${pageContext.request.contextPath}/user/insert",
            async:false,
            data :JSON.stringify({
                username : $("input[name='username']").val(),
                password: $("input[name='password']").val(),
                role : {
                    id : "",
                    name: $("select[name='name']").val()
                }
            }),
            contentType: "application/json;charset=UTF-8",
          /*如果不寫這個,仔細看後臺會出現Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported   */ 
            dataType:"json",
            success  :function (res) {
                console.log(res);
                if(res==100){
                    $("#msg").html("<font size='60px'> success </font>").show(700).delay(3000).hide(500);
                }else {
                    $("#msg").html("<font size='60px'>  fail </font>").show(700).delay(3000).hide(500);
                }
                window.location.href="http://localhost:8080/user/findall?page=1"
            },
            error:function () {
                $("#msg").html("<font size='60px'>  fail </font>").show(700).delay(3000).hide(500);
                window.location.href="http://localhost:8080/user/findall?page=1"
            }
        });
    }

後臺用@RequestBody接收, @RequestBody只接收JSON物件的字串
@ResponseBody
@RequestMapping(value = "/insert",method = RequestMethod.POST)
public String insert(@RequestBody User user){
   int result=this.userSerivce.insert(user);
   if(result==0){
       return "101";
   }
   return "100";
}