ajax与thymeleaf分别实现数据传输
小杰笔记篇:
1:第一种:利用Model和thymeleaf引擎来完成:
Controller层:
@CrossOrigin//解决跨域问题 @Controller public class UserController { @Autowired private UserMapper userMapper; @RequestMapping({"/","/index"}) public String queryUserList(Model model){ List<User> users = userMapper.queryList(); model.addAttribute("msg",users); return "index"; }
html:引入引擎
<!DOCTYPE html> <html lang="en"xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--/*@thymesVar id="msg" type=""*/--> <p th:text="${msg}"></p> </body> </html>
第二种方式:ajax:
第一步:创建User实体类假装数据库里面的数据:
@Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String name; private Integer tid; }
第二步:Controller层:
@ResponseBody @RequestMapping("/jie") public List<User> ajax2(){ List<User> list=new ArrayList<>(); list.add(new User(1,"杰",5)); list.add(new User(2,"杰",6)); list.add(new User(3,"杰",7)); list.add(new User(4,"杰",8)); return list; }
第三步:编写html:Jquery我这边下载文件导入
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.1.0.js"></script> </head> <body> <input type="button" id="btn" value="获取数据"> <table width="80%" align="center"> <tr> <td>id</td> <td>姓名</td> <td>编号</td> </tr> </table> <table id="con"> </table> </body> </html>
JavaScript:
<script> $(function () { $("#btn").click(function () { $.post({ url:"http://localhost:8080/jie", success: function (data) { console.log(data) var html=""; for (var i = 0; i <data.length ; i++) { html+= "<tr>" + "<td>" + data[i].id + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].tid + "</td>" + "</tr>" } $("#con").html(html); } }) })}) </script>
结果:
小杰笔记记录一下