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);
}
});
需要注意的两点:
data
参数需要使用JSON.stringify()
方法序列化成JSON字符串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字符串并反序列化成相应类的对象