局部刷新
一般我們做web項目時,我們在網頁上點擊下一頁或者跳轉頁面的時候,是將請求返還給後臺,然後後臺將數據傳回前端,並返回頁面。這時候你會發現頁面被重新打開,也就是整個頁面刷新了一次。
細心的人會發現瀏覽器的刷新按鈕會變動一下,這時候的頁面不再是原來的頁面,而是重新打開的一個頁面。
那麼,怎麼使頁面該刷新的地方刷新,不需要刷新的地方不動呢?
這就需要ajax請求來實現局部刷新了,只要用了局部刷新,會發現特別的高大上-.-,
用了一時爽,一直用一直爽。
代碼
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.springframework.org/schema/jdbc">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<div>
<span>該區域不會被刷新</span>
<Button id="button">刷新</Button>
<div id="child_view">
<span>該區域會被刷新</span>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type = "text/javascript" th:inline="javascript">
/*<![CDATA[*/
var basePath = /*[[${#httpServletRequest.getScheme() + "://" + #httpServletRequest.getServerName() + ":" + #httpServletRequest.getServerPort() + #httpServletRequest.getContextPath()}]]*/;
$('#button').bind('click', function () {
refresh();
});
function refresh() {
$.ajax({
url: basePath + '/index/refresh',
type: 'post',
dataType: 'text',
data: {
},
cache: false,
async: true,
success: function (data) {
$("#child_view").empty();
$("#child_view").append(data);
}
});
}
/*]]>*/
</script>
</body>
</html>
因爲是使用了thymeleaf框架,所以要加上th:inline="javascript"
,並且還要加上
/*<![CDATA[*/
var basePath = /*[[${#httpServletRequest.getScheme() + "://" + #httpServletRequest.getServerName() + ":" + #httpServletRequest.getServerPort() + #httpServletRequest.getContextPath()}]]*/;
js代碼
/*]]>*/
因爲是使用jqury,所以需要引用jqury
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
basePath用來url拼接,請求路徑前面加上basePath就好了,如basePath + '/index/refresh'
refresh.html
<div id="child_view">
<span>刷新的數據</span>
</div>
indexController跳轉到index頁面方法
@RequestMapping("/index")
public String toIndex(){
return "index";
}
indexController刷新數據方法
@RequestMapping("/index/refresh")
public String refresh(){
return "refresh";
}
運行
進入index頁面,當點擊button時候,child_view中的數據便會被refresh.html中的數據填充。