局部刷新
一般我们做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中的数据填充。