场景:删除一条信息后,刷新局部信息,不用刷新整个页面
testPartialRefresh.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf局部刷新</title>
</head>
<body>
<button id="btn2" th:onclick="btnTwo()">点击我改变部分页面内容</button>
<br/>
<button id="btn1" th:onclick="btnOne()">页面局部刷新</button>
<div id="div_test">
我是初始页面内容
</div>
<div th:fragment="visit" id="visit">
后台返回数据:<span th:text="${msg}"></span>
</div>
<!--jquery-->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<!--axios-->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!--baseURL 动态获取网页前缀如 http://localhost:8080/demo03 -->
<script th:src="@{/static/js/commons/common.js}"></script>
<script type="text/javascript">
function btnOne(){
axios({
method: "post",
url: "/test/pr",
params:{
}
}).then(function (response) {
//alert(response.data)
console.log(response.data)
//javascript 原生操作
//document.getElementById("visit").innerHTML=response.data;
//jquery
$("#visit").html(response.data);
}).catch(function (error){
if (error.response) {
// 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 请求已经成功发起,但没有收到响应
// `error.request` 在浏览器中是 XMLHttpRequest 的实例,
// 而在node.js中是 http.ClientRequest 的实例
console.log(error.request);
} else {
// 发送请求时出了点问题
console.log('Error', error.message);
}
console.log(error.config);
})
}
function btnTwo(){
document.getElementById("div_test").innerHTML = "<p>如果我没有了,页面就是刷新了</p>";
}
</script>
</body>
</html>
testPartialRefresh.java
package com.wenrui.crud.test;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.UUID;
/**
* @Author: huWenRui
* @CreateTime: 2022-12-15 18:46
* @Description:
* https://blog.csdn.net/lianghecai52171314/article/details/107725410
*/
@Controller
public class testPartialRefresh {
/**
* 跳转到局部刷新测试页面
* @return
*/
@GetMapping("/testPartialRefresh")
public String showPartialRefresh(){
return "test/testPartialRefresh";
}
/**
* 局部刷新
* @param model
* @return
*/
@PostMapping("/test/pr")
public String partialRefresh(Model model){
model.addAttribute("msg", UUID.randomUUID().toString());
return "test/testPartialRefresh::visit";
}
}
Axios发送请求,后台返回一个代码片段,jquery插入到页面

后台返回一个代码片段,传参数msg值是自动UUID生成的随机数
