用 ajax 替換片段
如果你想要替換網站的部分內容,ajax 是一種簡單的方法。
你要根據所選值替換內容的 website.html :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Index</title>
</head>
<body>
<select id="selection">
<option>Content 1</option>
<option>Content 2</option>
</select>
<div id="replace_div">
Content goes here
</div>
<!-- JQury from Google CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
//call function when page is loaded
getContent();
//set on change listener
$('#selection').change(getContent);
function getContent() {
//create url to request fragment
var url = /content/;
if ($('#selection').val() === "Content 1") {
url = url + "content1";
} else {
url = url + "content2";
}
//load fragment and replace content
$('#replace_div').load(url);
}
})
</script>
</body>
</html>
並且 content.html 包含你要根據所選值包含的片段:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div th:fragment="content1">
This is Content 1
</div>
<div th:fragment="content2">
This is Content 2
</div>
</body>
</html>
最後但並非最不重要的是 Spring MVC ContentController.java :
@Controller
@RequestMapping("content")
public class ContentController {
@RequestMapping("")
public String loadContent() {
return "website";
}
@RequestMapping("content1")
public String getContent1() {
return "content::content1";
}
@RequestMapping("content2")
public String getContent2() {
return "content::content2";
}
}