springmvc处理ajax请求,返回json数据
①在springmvc方法上添加@ResponseBody注解,springmvc会将数据转换成json并返回;
@ResponseBody //指定返回json数据,不跳转页面 @RequestMapping("/list") public List<User> list(User user){ System.out.println("获取到异步请求数据:"+user); //todo 根据条件做数据库查询,返回结果集合 ArrayList<User> users=new ArrayList<>(); users.add(new User(1,"james",18,"男")); users.add(new User(2,"姚明",40,"男")); users.add(new User(3,"科比",46,"男")); return users; }
list.jsp页面中代码为:
<body> <input type="button" id="btn" value="异步加载数据"/> <script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script> <script> $(function ($) { $("#btn").click(function () { $.ajax({ url:"${pageContext.request.contextPath}/list", type:"post", data:{"name":"james","age":18}, dataType:"json", success:function (result) { alert("请求成功!") console.log(result) } }) }) }) </script> </body>
②如果contentType=”application/json”时,在方法的参数前添加@RequestBody注解,获取传递的json字符串,并封装到对象中;
@ResponseBody //指定返回json数据,不跳转页面 @RequestMapping("/list") public List<User> list(@RequestBody(required=false) User user){ System.out.println("获取到异步请求数据:"+user); //todo 根据条件做数据库查询,返回结果集合 ArrayList<User> users=new ArrayList<>(); users.add(new User(1,"james",18,"男")); users.add(new User(2,"姚明",40,"男")); users.add(new User(3,"科比",46,"男")); return users; }
list.jsp页面中代码为:
<body> <input type="button" id="btn" value="异步加载数据"/> <script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script> <script> $(function ($) { $("#btn").click(function () { var jsonObj={"name":"james","age":18}; $.ajax({ url:"${pageContext.request.contextPath}/list", type:"post", data:JSON.stringify(jsonObj),//json字符串 将json对象转化为字符串 dataType:"json", contentType:"application/json",//指定以json方式传输数据 success:function (result) { alert("请求成功!") console.log(result) } }) }) }) </script> </body>