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字符串并反序列化成相应类的对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值