ajax傳輸Json的正確方式

1.jquery的方式

let data = {
	"name" : "xxx",
	"age"  : 20
}
$.ajax({
    url: 'localhost:8080/api/xxxxx',
    dataType: 'json',
    type: 'post',
    data: JSON.stringify(data),
    contentType: 'application/json;charset=utf-8',
    success: function (resp) {
        console.log(resp);
    }
});

需要注意的兩點:

  1. data參數需要使用JSON.stringify()方法序列化成JSON字符串
  2. contentType需要顯示指定爲'application/json;charset=utf-8',這樣瀏覽器纔會把需要傳輸的data認爲時JSON字符串傳輸,否則瀏覽器還是會將其作爲Form Data傳輸,這樣後端接收到的參數會出現反序列化錯誤。

2.axios方式

axios會自動將JS對象作爲Json類型傳輸,這樣就會極大的方便我們的編碼工作

    axios.post('localhost:8080/api/xxxxx',{
	"name" : "xxx",
	"age"  : 20
   }).then(response => (this.info = response))
     .catch(function (error) { // 請求失敗處理
       	console.log(error);
   });

axios發送post請求時,會自動將HTTP Request中的contentType設置爲'application/json;charset=utf-8',這樣就能保證後端接收到的參數自動轉化爲JSON形式。

附:Java後端SpringMVC接收代碼

    @RequestMapping("/api/xxxxx")
    @ResponseBody
    public HttpResult register(@RequestBody UserDto userDto) {
        log.info("接口入參:{}", userDto);
        HttpResult httpResult = userService.register(userDto);
        return httpResult;
    }

這裏直接用@RequestBody註解就可以實現接收Json字符串並反序列化成相應類的對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章