赞
踩
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"); } })
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"); } })
后端写法:
@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})"; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。