thymeleaf异步刷新

文章讲述了在开发中实现置顶和取消置顶功能时,为了避免频繁的window.location.reload()造成的服务器资源消耗,采用异步刷新和事件委托技术。Java控制器中通过Ajax请求处理置顶和取消置顶逻辑,并确保功能在页面动态刷新时仍能正常工作。

业务描述:开发置顶功能时,需要利用后台的数据判断当前需要置顶或取消置顶,类似于关注和取消关注的功能,但该功能的页面复杂,以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";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

twfplayer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值