ajax中设置contentType: "application/json",后端参数如何接收
Posted 火星的巧克力
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax中设置contentType: "application/json",后端参数如何接收相关的知识,希望对你有一定的参考价值。
这里contentType: "application/json还未设置
1.
function testRequestBody() { var book = new Object(); var id = 1; var name = "Spring MVC企业应用实践"; book.id = 1; book.name = "Spring MVC企业应用实践"; $.ajax({ url:"${pageContext.request.contextPath}/json/testRequestBody", type:"post", dataType:"json", async:true, data: { "id":id,"name":name}, success:function (data) { console.log(data); }, error:function () { alert("数据发送失败"); } }); }
Controller代码
@RequestMapping(value = "/testRequestBody",method = RequestMethod.POST) public @ResponseBody Object testRequestBody(String id, String name){ logger.info("接收到的ajax数据:"+id+" "+name); List<Book> bookList = new ArrayList<Book>(); bookList.add(new Book(1,"语文","lzy")); bookList.add(new Book(2,"数学","liziy")); return bookList; }
控制台打印的日志信息 testRequestBody5 接收到的ajax数据:1 Spring MVC企业应用实践
数据接受正常
2.
前端数据 data: { "id":id,"color":name},
如果后端参数使用的@RequestParam标注 那么前端一定要有与之对应的 如果没有Ajax 400
@RequestMapping(value = "/testRequestBody4",method = RequestMethod.POST) public @ResponseBody Object testRequestBody( @RequestParam("id") String id, @RequestParam("name")String name){ logger.info("接收到的ajax数据:"+id+" "+name); List<Book> bookList = new ArrayList<Book>(); bookList.add(new Book(1,"语文","lzy")); bookList.add(new Book(2,"数学","liziy")); return bookList; }
控制台打印的日志信息 org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.logException Handler execution resulted in exception: Required String parameter ‘name‘ is not present
设置contentType: "application/json data数据需要加入JSON.stringify()
data : JSON.stringify(book),
data : JSON.stringify({ "id":1,"name":"hhhh"}),
这两种都可以 只要属性名称对应 后端就可以接受
$.ajax({ url:"${pageContext.request.contextPath}/json/testRequestBody", type:"post", dataType:"json", contentType: "application/json", async:true, //data : JSON.stringify(book), data : JSON.stringify({ "id":1,"name":"hhhh"}), success:function (data) { console.log(data); }, error:function () { alert("数据发送失败"); } });
后端代码 需要用一个对象来接受参数
@RequestMapping(value = "/testRequestBody4",method = RequestMethod.POST) public @ResponseBody Object testRequestBody(@RequestBody Book book){ logger.info("接收到的ajax数据:"+book); List<Book> bookList = new ArrayList<Book>(); bookList.add(new Book(1,"语文","lzy")); bookList.add(new Book(2,"数学","liziy")); return bookList; }
控制台打印的日志信息 testRequestBody 接收到的ajax数据:{"id":1,"name":"hhhh","author":null}
以上是关于ajax中设置contentType: "application/json",后端参数如何接收的主要内容,如果未能解决你的问题,请参考以下文章
ajax 发送json数据时为什么需要设置contentType: "application/json”
如何在 ajax POST 请求中设置标头以包含 CSRF 令牌