假设我们有一个简单的网页,其中包含一个按钮和一个文本框,我们希望点击按钮后能够使用Ajax局部刷新文本框中的内容,以下是使用Thymeleaf实现局部刷新的例子:

  1. 创建一个Spring Boot项目,添加以下依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.5.1</version>
</dependency>
  1. 在src/main/resources/templates目录下创建一个index.html文件,添加以下内容:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Demo</title>
    <script src="/webjars/jquery/3.5.1/jquery.min.js"></script>
    <script th:inline="javascript">
        function refreshText() {
            $.ajax({
                type: "GET",
                url: "/refresh",
                success: function (data) {
                    $("#text").text(data);
                }
            });
        }
    </script>
</head>
<body>
    <button onclick="refreshText()">Refresh Text</button>
    <br><br>
    <span id="text" th:text="${text}"></span>
</body>
</html>
  1. 在src/main/java目录下创建一个HomeController.java文件,添加以下内容:
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("text", "Hello Thymeleaf!");
        return "index";
    }

    @GetMapping("/refresh")
    @ResponseBody
    public String refresh() {
        return "Thymeleaf Demo Refreshed!";
    }

}
  1. 启动应用程序,访问http://localhost:8080/,点击按钮即可实现局部刷新。

在上面的例子中,我们使用Thymeleaf的th:text属性将文本框的内容绑定到模型中的text属性。当用户点击按钮时,我们使用jQuery发送一个Ajax请求到服务器上的/refresh端点,服务器将返回一个字符串,该字符串将更新文本框中的内容。我们使用jQuery的$("#text").text(data)来更新文本框的内容

用thymeleaf实现局部刷新给个例子

原文地址: https://www.cveoy.top/t/topic/dHyB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录