ajax中设置contentType: "application/json",后端参

时间:2020-12-17 18:32:06

javaScript部分 

  这里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}