Thymeleaf th:fragment局部刷新

目录

  • 一. 前期准备
  • 二. Controller
  • 三. HTML
  • 四. JS
  • 五. 效果


一. 前期准备

import lombok.Data;

@Data
public class Test14SubForm {

    private String title;

    private String name;

    private Boolean recommend;

    private Boolean published;
}
import lombok.Data;
import java.util.List;

@Data
public class Test14Form {
	
	// 组合
    private List<Test14SubForm> entityList;

    private String id;
}

二. Controller

  • ModelAndView: 页面初始化时,指定跳转页面,并且绑定数据到Thymeleaf中
  • Model: 局部刷新时携带数据到Thymeleaf中
  • return HTML名称 :: 片段名称: 用来指定局部刷新的区域
import com.example.jmw.form.Test14Form;
import com.example.jmw.form.Test14SubForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/test14")
public class Test14Controller {

    @GetMapping("/init")
    public ModelAndView init() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("test14");

        // 准备数据
        Test14SubForm test14SubForm1 = new Test14SubForm();
        test14SubForm1.setName("贾飞天");
        test14SubForm1.setTitle("人的一生");
        test14SubForm1.setPublished(false);
        test14SubForm1.setPublished(false);
        Test14SubForm test14SubForm2 = new Test14SubForm();
        test14SubForm2.setName("枫叶红");
        test14SubForm2.setTitle("程序员进阶");
        test14SubForm2.setPublished(false);
        test14SubForm2.setPublished(true);

        List<Test14SubForm> dataEntityList = Arrays.asList(test14SubForm1, test14SubForm2);
        Test14Form test14Form = new Test14Form();
        test14Form.setEntityList(dataEntityList);

        modelAndView.addObject("entity", test14Form);
        return  modelAndView;
    }

    @PostMapping("/testPartFlush")
    public String testPartFlush(@RequestBody Test14Form form, Model model) {
		
		System.out.println(form.getId());  // 110120

        // 准备数据
        Test14SubForm test14SubForm1 = new Test14SubForm();
        test14SubForm1.setName("张三");
        test14SubForm1.setTitle("摸鱼之王");
        test14SubForm1.setPublished(true);
        test14SubForm1.setPublished(true);
        Test14SubForm test14SubForm2 = new Test14SubForm();
        test14SubForm2.setName("李四");
        test14SubForm2.setTitle("入门到放弃");
        test14SubForm2.setPublished(false);
        test14SubForm2.setPublished(false);

        List<Test14SubForm> dataEntityList = Arrays.asList(test14SubForm1, test14SubForm2);
        Test14Form test14Form = new Test14Form();
        test14Form.setEntityList(dataEntityList);

        // 把要局部刷新的数据返回到前端定义好的片段中
        model.addAttribute("entity", test14Form);

        /*
         * 其中test14为html的名称
         * dataList为th:fragment片段的名称
         */
        return "test14 :: dataList";
    }
}

三. HTML

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <script type="text/javascript" th:src="@{/js/public/jquery-3.6.0.min.js}">script>
    <style>
        .fontColor1 {
            color: red;
        }

        .fontColor2 {
            color: yellow;
        }
    style>
    <title>testtitle>
head>
<body>
    <button id="flushBtn">thymeleaf局部刷新表格button>
    <hr>
    <div id="content" th:object="${entity}">
        
        <table id="table" th:fragment="dataList">
            
            <thead>
                <tr>
                    <th>行号th>
                    <th>标题th>
                    <th>分类th>
                    <th>推荐th>
                    <th>文章状态th>
                tr>
            thead>
            
            <tbody>
                
                <tr th:each="data, status: ${entity.entityList}">
                    <td th:text="${status.index}">1td>
                    <td th:text="${data.title}">小技巧td>
                    <td data-test="blogName">[[${data.name}]]td>
                    
                    <td th:text="${data.recommend} ? '是' : '否' ">td>
                    
                    <td th:class="${data.published} ? 'fontColor1' : 'fontColor2' ">[[${data.published} ? '发布' : '草稿' ]]td>
                tr>
            tbody>
        table>
    div>
body>

四. JS

  • 发送Ajax请求,局部刷新Thymeleaf片段,后台向Ajax返回的是字符串
  • Ajax请求不能指定返回值为json,否则无法获取局部刷新之后的HTML字符串
  • 若局部刷新的区域有事件绑定,在DOM重绘之后,事件会失效,需要重新进行绑定
$(function() {
     EventBind();
 });

$("#flushBtn").click(() => {

    const url = `http://localhost:8080/test14/testPartFlush`;
    const data = {
        id: "110120",
    };

    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(data),
        contentType : 'application/json;charset=utf-8',
        success: function (data, status, xhr) {

            console.log("====后台返回的数据开始====");
            console.log(data);
            console.log("====后台返回的数据结束====");

            // 其中data为后台返回的局部刷新之后的DOM字符串,我们将其添加到待重绘区域
            $("#table").html(data);

            // 表格重绘会导致原先绑定的事件失效,因此需要重新进行事件绑定
            EventBind();
        }
    });
});

// 事件绑定
function EventBind() {
    $("[data-test='blogName']").click(function () {
        console.log($(this).text());
    });
}

五. 效果

Thymeleaf th:fragment局部刷新_第1张图片

你可能感兴趣的:(#,Thymeleaf,Thymeleaf)