Ajax数据到后端页面不正确解析
Caused by: com.fasterxml.jackson.core.JsonParseException:Unrecognized token ‘type’: was expecting (JSON String, Number, Array, Object or token ‘null’, ‘true’ or ‘false’)
为了确保数据被正确格式化为JSON对象,并且可以被服务器解析,可以使用jQuery的JSON.stringify()方法将数据转换为字符串,并将内容类型头设置为“application/ JSON”。还可以将AJAX请求中的dataType参数指定为“json”,以表明预期的响应数据是json格式的。 下面是一个示例代码片段,展示了如何做到这一点:
<script> $(function(){ $(#btnPOST).on(click,function(){ $.ajax({ url:http://localhost:80/books, type:"post", contentType:"application/json;charset=utf-8", dataType:JSON, data:JSON.stringify({ "type":"SPringboot", "name":"SPringboot", "description":"SPringboot" }), success:function(res){ console.log(res) }, error:function(error){ console.log(error) } }) }) }) </script>
注意,如果你的后端在Spring MVC中使用@RequestBody注释,那么它只能绑定到一个JSON字符串,而不是一个JSON对象。因此,需要使用json.stringify(data)方法将对象转换为字符串,并指定"json" dataType参数。