当前位置:   article > 正文

SpringBoot和AJAX_springboot ajax

springboot ajax

ajax写法不同,springboot接收参数的方式也不同

ajax如果这样写:
有两点注意:contentType指定为json,那么data需要用stringify包装,否则@RequestParam就要报错了(返回状态码400)
另外,json数据不能用@RequestParam接收,因为@RequestParam接收的是url后面跟着的参数,而不是body中的

 $.ajax({
     url:"http://127.0.0.1:8088/hello/u2",
     data: JSON.stringify({
         name: "adam",
         callback: "fuck"
     }),
     type: "post",
     contentType: "application/json",
     success: function (data) {
         console.log("收到了?");
         console.log(data);
     },
     error: function () {
         console.log("error");
     }
 })

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

ajax的默认写法:
不能用@RequestBody接收,因为无法解析原始的contentType:application/x-www-form-urlencoded

 $.ajax({
     url:"http://127.0.0.1:8088/hello/u2",
     data: {
         name: "adam",
         callback: "fuck"
     },
     type: "post",
     success: function (data) {
         console.log("收到了?");
         console.log(data);
     },
     error: function () {
         console.log("error");
     }
 })

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

后端写法:

@Slf4j
@RestController
@RequestMapping("/hello")
public class SimpleController {

    @RequestMapping("/u1")
    public String u1(String name, String callback){
        log.info("有请求1");
        log.info("name:{}",name);
        log.info("callback:{}",callback);


        return callback+"({price:10})";
    }

    @RequestMapping("/u2")
    public String u2(@RequestBody Util thing){
        log.info("有请求2");
        log.info("name:{}",thing.getName());
        log.info("callback:{}",thing.getCallback());

        return thing.getCallback()+"({price:10})";
    }

    @RequestMapping("/u3")
    public String u3(@RequestParam("name") String name, @RequestParam("callback") String callback){
        log.info("有请求3");
        log.info("name:{}",name);
        log.info("callback:{}",callback);
        return callback+"({price:10})";
    }

    @RequestMapping("/u4")
    public String u4(HttpServletRequest req){
        log.info("有请求4");
        log.info("name:{}",req.getParameter("name"));
        log.info("callback:{}",req.getParameter("callback"));

        return req.getParameter("callback")+"({price:10})";
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/652172
推荐阅读
相关标签
  

闽ICP备14008679号