需求
现在我们有这样一个需求:提交表单后,只刷新某页面的一部分内容,不刷新整个页面。
知识点:使用th:fragment,ajax技术
前端代码(blog.html):
以下代码展示了评论区 (只是整个html页面的一小部分),如果用户填写了评论表单并提交了,那么就会局部刷新这个评论区,刷出来这条新的留言(不会刷新整个页面)
<div th:fragment="commentList">
<!--循环读取所有评论列表-->
<div class="comment" th:each="comment : ${comments}">
<span th:text="${comment.nickname}">评论用户的昵称</span>
<span th:text="${comment.content}">评论内容</span>
</div>
</div>
提交评论的form表单
<!--提交留言的表单-->
<div id="comment-container">
<input type="hidden" name="blog.id" th:value="${blog.id}">
<div>
<!--输入评论内容的区域-->
<textarea name="content" placeholder="请输入评论信息..."></textarea>
</div>
<input type="text" name="nickname" placeholder="如何称呼您" >
<button type="button">发布</button>
</div>
点击发布按钮,就会执行下面的js代码,将表单提交(使用ajax方式):
<script>
function postData() {
//使用ajax的方式 向Controller提交表单
$("#comment-container").load("[[@{/comments}]]",{
"blog.id" : $("[name='blog.id']").val(),
"nickname": $("[name='nickname']").val(),
"content" : $("[name='content']").val()
},function (responseTxt, statusTxt, xhr) { //回调函数
//提交表单之后,调用clearContent()方法 会清理掉之前表单填写的东西
clearContent();
});
}
</script>
注意看上面的 load("[[@{/comments}]]",
想调用controller层的方法,是这样调用的(jQuery和thymeleaf交互)
这里需要用Ajax的方式来实现局部刷新,所以得懂得一点js的知识
表单提交后走的Controller:
//提交评论表单,点击发布按钮走的post方法
@PostMapping("/comments")
public String post(Comment comment, HttpSession session) {
//将评论信息储存到数据库
commentService.saveComment(comment);
//redirect到上面那个局部刷新的方法
return "redirect:/comments/" + blogId;
}
//该方法负责局部刷新页面的评论区
@GetMapping("/comments/{blogId}")
public String comments(@PathVariable Long blogId, Model model) {
//将数据库里面所有的评论拿出来,回传给前端页面
model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
//局部刷新的语法。前面是html页面,后面是th:fragment的值
return "blog :: commentList";
}
评论表单提交后,会先走第一个方法 public String post ,将新的评论保存到数据库。
然后第一个方法会重定向到第二个方法里面去,第二个方法将数据库里面所有的评论拿出来,回传给前端页面,局部刷新页面的评论区。
注意 局部刷新的语法:前面是html页面(我的html页面就叫blog,html),后面是th:fragment的值(看最开头th:fragment的定义)
return "blog :: commentList";
到此为止thymeleaf局部刷新的功能就实现了。这个Demo虽然简单,但是也能体现出局部刷新,以及ajax。如果解决了您的问题,留个赞再走吧