var data = {"data": "save功能测试"};
$.ajax({
type: "post",
dataType: "json",
contentType: "application/json",
url: '',
data: data,
success: function (res) {
console.log(res.data);
}
});
一次平常的ajax请求,data是一个json格式的数据,然后请求报错:
{"timestamp":"2022-02-23 10:44:42","status":400,"error":"Bad Request","message":"JSON parse error: Unrecognized token 'data': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'data': was expecting ('true', 'false' or 'null')\n at [Source: (PushbackInputStream); line: 1, column: 6]","path":""}
然后我们只需要使用 JSON.stringify() 方法,将json格式转成json字符串格式(加上了引号),问题就迎刃而解。
即:
var data = {"data": "save功能测试"};
$.ajax({
type: "post",
dataType: "json",
contentType: "application/json",
url: '',
data: JSON.stringify(data),
success: function (res) {
console.log(res.data);
}
});
试着分析原因,打印stringify()前后的data:
{data: "save功能测试"}
{"data":"save功能测试"}
发现json赋值给data对象的时候,data对象将json里面的key值的引号去掉了,导致请求失败,使用JSON.stringify()后会将key值的引号加上。
此外,POST请求时,需加上 contentType: “application/json”,否则会报415错误。
如果是get请求,则不需要:
var data = {"data": "save功能测试"};
$.ajax({
type: "get",
dataType: "json",
url: '',
data: data,
success: function (res) {
console.log(res.data);
}
});
最后总结:
- post:需要 contentType: “application/json” ,需要 JSON.stringify(),后端接收使用 @RequestBody接收参数。
- get:不需要 contentType: “application/json” ,不需要 JSON.stringify(),后端接收使用 @RequestParam接收参数。