暑假撸系统6- Thymeleaf ajax交互!

本来用Thymeleaf也没想着深度使用ajax,就是用也是非常传统的ajax方式提交然后js控制修改下变量。闲来无事的时候看Thymeleaf的教程发现一哥们的实现方式,以及实现思路,堪称惊奇,先说说主角吧! 就是这货 th:fragment,先来看下官方的解释。

模板中,经常希望从其他模板中包含公共部分,如页眉,页脚,公共菜单等部分,为了做到这点,Thymeleaf 可以使th:fragment 属性来定义被包含的模版片段,以供其他模版包含。大白话就是先定义好一个小片段,需要的时候动态的把这玩意找出来然后插入到指定的地方。恩,这个操作貌似可以尝试下和jq的动态加载搞一起,那不就是ajax操作了,而且如果能实现连修改的变量的js都不用写了,Thymeleaf直接帮忙完成了,说干就干。代码如下,前端代码!

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>thymeleaf局部刷新</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
</head>
<body>
<div>
    <span style="margin:0 auto;font-size: 26px" th:text="${refresh}"></span>
    <button onClick="localRefresh()">点击刷新表格</button>
</div>
 
<!-- 需要局部刷新的部分,设置了th:fragment="table_refresh" -->
<div id="table_refresh" style="text-align: center;margin:0 auto; 900px" th:fragment="table_refresh"> <!--这里世一个重点-->
    <h1 th:text="${title}"></h1>
    <table width="100%" border="1" cellspacing="1" cellpadding="0">
        <tr>
            <td>Author</td>
            <td>Book</td>
            <td>Url</td>
        </tr>
        <tr th:each="book : ${books}">
            <td th:text="${book.author}"></td>
            <td th:text="${book.title}"></td>
            <td th:text="${book.url}"></td>
        </tr>
    </table>
</div>
</body>
<script>
    function localRefresh() {
        // 装载局部刷新返回的页面
        $('#table_refresh').load("/student/stuchapter/local");   //注意这里世jq的方法  可不是模板的神器方法!
    }
</script>
</html>
//下面是测试ajax用的  
 @RequestMapping("test")
 public String globalRefresh(ModelMap model) {
     List<Map<String,String>> lists = new ArrayList<>();
     Map<String,String> map = new HashMap<>();
     map.put("author", "曹雪芹");
     map.put("title", "《红楼梦》");
     map.put("url", "www.baidu.com");
     lists.add(map);

     // 用作对照
     model.addAttribute("refresh", "我不会被刷新");
     
     model.addAttribute("title", "我的书单");
     model.addAttribute("books", lists);
     return prefix+"/test";  
     
}
 
 /**
  * 局部刷新,注意返回值
  * @param model
  * @return
  */
 @RequestMapping("local")
 public String localRefresh(ModelMap model) {
     List<Map<String,String>> lists = new ArrayList<>();
     Map<String,String> map = new HashMap<>();
     map.put("author", "罗贯中");
     map.put("title", "《三国演义》");
     map.put("url", "www.baidu.com");
     lists.add(map);

     model.addAttribute("title", "我的书单");
     model.addAttribute("books", lists);
     // "test"是test.html的名,
     // "table_refresh"是test.html中需要刷新的部分标志,
     // 在标签里加入:th:fragment="table_refresh"
     return prefix+"/test::table_refresh";
 }

是不是很神奇!整个界面都没有js动态修改变量,但是整体却又完美实现页面的动态更改!

 点击后

 马上应用到自己的项目中!巨好用!

 

 

原文地址:https://www.cnblogs.com/liuadong/p/13372260.html