thymeleaf异步刷新

发布时间 2023-08-28 15:49:25作者: twfplayer

业务描述:开发置顶功能时,需要利用后台的数据判断当前需要置顶或取消置顶,类似于关注和取消关注的功能,但该功能的页面复杂,以window.location.reload();的方式过于消耗服务器资源,因此采用了异步刷新的方式处理

html

<!-- 父级元素,不受异步刷新影响-->
<div id="buttonsContainer">
 <input type="hidden" id="postId" th:value="${post.id}">
 <!-- th:fragment html模板-用于异步刷新-->
 <div id="postTop" th:fragment="postTop">
  <input type="hidden" id="postType" th:value="${post.type}">
  <button type="button" id="topBtn"
     th:text="${post.type==1?'取消置顶':'置顶'}">置顶
  </button>
 </div>
</div>

js

// 使用事件委托的方式,避免异步刷新导致的事件绑定失效问题
// 将事件绑定在不受异步刷新影响的父级元素上,不论按钮如何被动态刷新或重新绑定,事件只会在父级元素上执行一次
// 若直接绑定在按钮上,将会导致按钮只能执行一次,异步刷新后事件监听器被删除,按钮失效
$(function () {
    $("#buttonsContainer").on("click", "#topBtn", setTop);
});

//置顶或取消置顶
function setTop() {
    var postType = $("#postType").val();
    if (postType == 0) {
        $.post(CONTEXT_PATH + "/discuss/top",
            { "id": $("#postId").val() },
            function (data) {
                    $("#postTop").html(data);
            }
        );
    } else if (postType == 1) {
        $.post(CONTEXT_PATH + "/discuss/untop",
            { "id": $("#postId").val() },
            function (data) {
                    $("#postTop").html(data);
            }
        );
    }
}

java::controller

    /**
     * 置顶
     * @param id
     * @return
     */
    @RequestMapping(path = "/top", method = RequestMethod.POST)
    public String setTop(int id, Model model) {
      // 置顶相关逻辑
        DiscussPost post = new DiscussPost();
        post.setType(POST_TOPPING);
        // 注;此处一定使用实体进行传参,否则会报500,
        model.addAttribute("post", post);
        return "/site/discuss-detail::postTop";
    }
    /**
     * 取消置顶
     * @param id
     * @return
     */
    @RequestMapping(path = "/untop", method = RequestMethod.POST)
    public String unTop(int id,Model model) {
      // 取消置顶相关逻辑
        DiscussPost post = new DiscussPost();
        post.setType(POST_NORMAL);
        model.addAttribute("post", post);
        return "/site/discuss-detail::postTop";
    }