第一步:直接在templates目录下创建文件partialRefresh.html:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf局部刷新</title>
<script th:src="@{/js/jquery3.3.1.js}"></script>
</head>
<body>
<button id="btn1">局部刷新1</button>
<button id="btn2">局部刷新2</button>
<div th:fragment="visit" id="visit"> <!--① -->
后台返回数据:<p th:text="${msg}"></p>
</div>
<script type="text/javascript">
$("#btn1").click(function () {
$.ajax({
url:"pr",
type:"post",
success:function (data) {
$("#visit").html(data);
}
})
});
$("#btn2").click(function () {
$("#visit").load("pr");
});
</script>
</body>
</html>
注:编号①必须指定id,且id的值得和th:fragment的值一致。
第二步:后台控制器:
@GetMapping("/showpr")
public String showPR(){
return "partialRefresh";
}
@RequestMapping("/pr")
public String partialRefresh(Model model){
model.addAttribute("msg",UUID.randomUUID().toString());
return "partialRefresh::visit";
}