学习目标:
使用Thmyleaf模板引擎和Ajax实现html界面的局部刷新
效果预览:
本来想着直接把效果预览的视屏放到服务器的静态资源下,由nginx转发跳转。结果显示不了,csdn也不支持。
那只能上截图了。
截图一,我在选择完文件之后,界面是这样的
截图二,当点击【点我】 按钮的时候,我的逻辑是通过agix发送一个异步请求,进行局部刷新。
局部刷新实现:
一开始接触Ajax的时候,第一个案例就是,点击按钮,ajax异步请求到后台,获取数据,拿到数据之后,在返回成功的函数中,一般我们是这样写的。在此之前先引入jquery.js,因为这儿我不不是通过写原生的ajax实现。
$.ajax({
url: url,
type: 'POST',
data: ,
success: function (data) {
//这部分就是实现刷新界面的效果的,
//先通过id或者class等获取到这个标签,再通过繁琐的拼接,
//将标签和数据整合起来实现了局部刷新的效果。
}
})
Thmyleaf,Ajax实现局部刷新。
代码实现---前端
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<script
src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js">
</script>
<script>
$(document).ready(function(){
$("#sub1").click(function(){
$.ajax({
url:"/v1/usual/countegwdfrequency",
method:"get",
async:true,
success:function(result){
$("#egListFragmentId").html(result);
}});
});
});
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input id = "file" type="file" name="file"><br>
//表单提交前端加上csrf,因为spring security没有关闭csrf校验
//。跟局部刷新关系,当做主题部分展示。
//<input type="hidden" th:name="${_csrf.parameterName}"
th:value="${_csrf.token}"/>
</form>
<button id="sub1">提交</button>
<div id="egListFragmentId" th:fragment="egListFragment">
<div class="comment" th:each="eg : ${egFrequencyList}">
<span th:text="${eg.egWord}"></span> :
<span th:text="${eg.frequency}"></span>
</div>
</div>
</body>
</html>
代码展示----后端
//统计单词频率
@GetMapping(value = "/countegwdfrequency")
public String countEgWordFrequency(Model model) {
List<EgFrequencyImpl> egFrequencyList = new ArrayList<>();
egFrequencyList.add(new EgFrequencyImpl("a",1));
egFrequencyList.add(new EgFrequencyImpl("b",2));
egFrequencyList.add(new EgFrequencyImpl("c",3));
model.addAttribute("egFrequencyList", egFrequencyList);
return "usual2 :: egListFragment";
//返回的应该是usual2 页面局部fragment部分。按照常理来说model中
//的数据应该只能在fragment部分解析展示
//其他地方解析不了,不能确定,感兴趣的同学可以尝试一下。
}