简而言之,就是当我发送一个请求到后端后拿到数据后返回当前 页面不会对整个页面进行重载而只对当前请求的模块进行刷新。
优势:
弊端:
th:fragment="刷新的标记"
首先我们需要先右键new一个springboot项目
配置pom依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>demo</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
配置yml文件
server: port: 8080 # Spring配置 spring: # 模板引擎 thymeleaf: # 禁用缓存 cache: false prefix: classpath:/templates/ suffix: .html mode: HTML encoding: utf-8
编写接口:
package com.example.demo.web; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.List; /** * @Program: demo * @ClassName WebController * @Author: LiuTao * @Description: SpringBoot+thymeleaf+ajax实现局部刷新测试接口类 * @Create: 2022-07-24 0:29 * @Version 1.0 **/ @Controller public class WebController { /** * @methodName: list * @description: 测试接口 * @Author LiuTao * @param [model] * @updateTime 2022/7/24 0:33 * @return java.lang.String * @throws **/ @RequestMapping("/list") public String list(Model model) { List lists = new ArrayList(); lists.add("aaaa"); lists.add("bbbb"); lists.add("cccc"); lists.add("dddd"); model.addAttribute("list",lists); return "index::list"; } }
在templates包下新建一个index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Title</title> <script th:src="@{/jquery.min.js}"></script> </head> <body> <button onclick="list()">获取列表</button> <table border="1" th:fragment="list" id="list" > <thead> <th>用户</th> </thead> <tr th:each="list:${list}"> <td>[[${list}]]</td> </tr> </table> </body> <script> function list(){ //第一种方法 // $('#search').load("/list"); //第二种方法 $.ajax({ url: "/list", type: 'POST', success: function (data) { $("#list").html(data); } }) } </script> </html>