1. 程式人生 > >ajax 前後端互動

ajax 前後端互動

1.前端

$.ajax({
    url: "http://localhost:8001/regist/regist",
    type: "post",
    /*date: JSON.stringify(registVO),
    contentType:"application/json",*/
    data:{
        "userName":$("#userName").val(),
        "password":$("#password").val()
    },
    dataType: "json",
    success: function (obj) {
        alert(obj);
    }
});

後端

@ApiOperation(value = "使用者註冊")
@RequestMapping(value = "/regist",method = RequestMethod.POST)
public JsonResult regist(RegistVO registVO) throws Exception{
    System.out.println("1232");
    System.out.println("123213123");

    logger.info("RegistController...regist...前端使用者註冊介面入參:[" + registVO.toString() + "]");

    return this.buildErrorResult();
}

2  前端

var registVO = {
    "userName":$("#userName").val(),
    "password":$("#password").val()
}
$.ajax({
    url: "http://localhost:8001/regist/regist",
    type: "post",
    date: JSON.stringify(registVO),
    contentType:"application/json",
    dataType: "json",
    success: function (obj) {
        alert(obj);
    }
});

後端

@ApiOperation(value = "使用者註冊")
@RequestMapping(value = "/regist",method = RequestMethod.POST)
public JsonResult regist(@RequestBody(required=false) RegistVO registVO) throws Exception{
    System.out.println("1232");
    System.out.println("123213123");

    logger.info("RegistController...regist...前端使用者註冊介面入參:[" + registVO.toString() + "]");

    return this.buildErrorResult();
}

結果: 第一種方法是可以的,但是第二種方法一直沒有成功  contentType:"application/json", 因為這種傳輸模式會影響跨域請求,導致後端一直接受不到資料是null

個人的想法,若有不對請指出