Laravel点赞功能如何实现不刷新页面即可更新数据?
代码调整步骤
1. 调整Blade模板代码
给点赞按钮增加类型标识属性,给计数元素增加专用类名方便JS定位,同时补全原代码缺失的a标签闭合标记:
<a href="/article/{{ $article->id }}?type=heart" class="comments-sub-header__item like-button" data-type="heart"> <div class="comments-sub-header__item-icon-count like-count"> {{ $article->like_heart }} </div> </a> <a href="/article/{{ $article->id }}?type=finger" class="comments-sub-header__item like-button" data-type="finger"> <div class="comments-sub-header__item-icon-count like-count"> {{ $article->like_finger }} </div> </a>
2. 调整后端控制器代码
在接口返回值中新增状态码和更新后的点赞数,方便前端直接做局部更新:
public function postLike($id, Request $request) { $article = Article::find($id); if(!$article){ return abort(404); } $type = $request->input('type'); if ($article->hasLikedToday($type)) { return response() ->json([ 'code' => 1, // 1代表重复点赞 'message' => 'You have already liked the Article '.$article->id.' with '.$type.'.', ]); } $cookie = $article->setLikeCookie($type); $article->increment("like_{$type}"); return response() ->json([ 'code' => 0, // 0代表点赞成功 'message' => 'Liked the Article '.$article->id.' with '.$type.'.', 'cookie_json' => $cookie->getValue(), 'like_count' => $article->{"like_{$type}"}, // 返回更新后的点赞数 ]) ->withCookie($cookie); }
3. 修改前端JS代码
删除全局刷新逻辑,替换为局部更新对应点赞数的逻辑:
$(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), }, }); $('.like-button').on('click', function(event) { event.preventDefault(); const $btn = $(this); // 防止重复点击 if($btn.hasClass('liked')) return; const href = $btn.attr('href'); const $countEl = $btn.find('.like-count'); $.ajax({ url: href, type: 'POST', dataType: 'json', success: function(res) { if (res.code === 0) { // 直接更新对应点赞数 $countEl.text(res.like_count); $btn.addClass('liked'); } else { alert('你今日已经为该内容点过赞了'); } }, error: function() { alert('点赞失败,请稍后重试'); } }); }); });
可选优化
- 页面初始化时读取cookie中的点赞记录,给已经点过赞的按钮默认添加
liked样式,用户刷新页面后也能直观看到自己的点赞状态 - 点赞过程中给按钮添加加载态,避免用户重复点击触发多次请求
内容的提问来源于stack exchange,提问作者chu
相关产品推荐
相关产品推荐

