【jQuery/Thymeleaf】在Thymeleaf页面用jQuery的Ajax方法取得后台数据显示在页面上
今天翻以前的笔记发现了其中的Dojo代码,它被后来的JQuery取代了,jQuery又被Vue/React要赶下台了,前台真是你未唱罢我登场,程序员每次不跟还不行,跟了把总是觉得新瓶装旧酒,腻歪了。
本文例程下载:
https://files.cnblogs.com/files/heyang78/myBank_thymeleaf_jQuery_Ajax_table210906_2051.rar
正文:
第一步:前台页面
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Show all students</title> <script type="text/javascript" src="js/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(function(){ $("#showBtn").click(function(){ $.ajax({ url: "allStus",// 请求的地址 data:{},// 请求参数--没有 type:"get",// 请求方式 dataType:"json",// 服务器返回的数据类型即为json对象 success: function(resp) { var students=resp; showStudents(students); }, timeout: 50000,// 超时时间,超时后会调用error后的函数 error: function(xhr, textStatus, errorThrown) { // 404 请求地址无效 if(XMLHttpRequest.status=='404'){ alert("404:请求地址"+url+"无效."); return; } var msg="xhr.readyState="+xhr.readyState+"\n"; msg+="xhr.status="+xhr.status+"\n"; msg+="textStatus="+textStatus+"\n"; msg+="errorThrown="+errorThrown+"\n"; alert(msg); } }); }); }); function showStudents(students){ var table=document.getElementById("myTable"); // remove remained rows var trs=table.childNodes; for(var i=trs.length-1;i>=0;i--){ table.removeChild(trs[i]); } // add new rows var n=students.length; for(var i=0;i<n;i++){ var stu=students[i]; var td1=document.createElement("td"); td1.appendChild(document.createTextNode(stu.id)); var td2=document.createElement("td"); td2.appendChild(document.createTextNode(stu.name)); var tr=document.createElement("tr"); tr.appendChild(td1); tr.appendChild(td2); table.appendChild(tr); } } </script> </head> <body> <h1>Show all students using jquery.</h1> <button id="showBtn">Show</button> <table border="1px" width="160px"> <caption>five students</caption> <thead> <tr><th>id</th><th>name</th></tr> </thead> <tbody id="myTable" > </tbody> </table> </body> </html>
以上代码需要说明的就是url: "allStus"一处,它与后台的JsonAction的一个相应函数是对应上的,其它代码无需赘述。
2.后台响应代码
@RestController public class JsonController { @Autowired private StudentMapper studentMapper; @GetMapping("/allStus") public List<Student> getAllStudents() { List<Student> students=studentMapper.findAll(); return students; } }
这个函数的注解是和页面上url对应上的,而返回数据貌似是对象,但由于@RestController的作用,直接变成了json对象,页面上resp对象就是它,往后直接用就可以了。
3.访问数据库的代码
@Mapper public interface StudentMapper { ...... @Select("select * from student") List<Student> findAll(); ...... }
这个就是简单查询student表。
有这三部分,前台页面通过Ajax方式传递请求到后台Rest控制器,然后访问数据库返回json对象的过程就齐活了。
--END--