如何防止重新加载页面后喜欢的图标类更改为常规?

How to prevent like icon class from changing to regular after reloading page?

提问人:Husnain 提问时间:10/9/2023 最后编辑:pmacfarlaneHusnain 更新时间:10/12/2023 访问量:11

问:

我有一个帖子的“赞”按钮。当用户喜欢该帖子时,数据库中的点赞数会递增,并且点赞图标类将更改为 solid。但是,当用户重新加载页面时,点赞图标类将更改为常规图标类,即使点赞计数在数据库中仍然正确。

我正在为喜欢的按钮使用以下代码:

<div class="like-container">
  <i
    class="fa-thumbs-up {% if post.liked_by_user %}fa-solid fa-xs{% else %}fa-regular fa-xs{% endif %} like-icon"
    id="like-icon-{{ post.id }}"
    data-post-id="{{ post.id }}"
    data-liked="{{ post.liked_by_user }}"
    onclick="handleLikeClick(this)"
  ></i>
  <span class="like-count">{{ post.count_likes() }} </span><b id="txt"> Likes</b>
</div>

这是 AJAX 代码

function handleLikeClick(likeIcon) {
  const postID = likeIcon.getAttribute('data-post-id');
  const liked = likeIcon.getAttribute('data-liked') === 'true';

  $.ajax({
    url: '/like_post',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ post_id: postID }),
    success: function (response) {
      // Update the like count and icon class based on the response
      const likeCountSpan = $(likeIcon).siblings('.like-count');
      likeCountSpan.text(response.like_count);
      if (response.liked_by_user) {
        $(likeIcon).removeClass('fa-regular').addClass('fa-solid');
      } else {
        $(likeIcon).removeClass('fa-solid').addClass('fa-regular');
      }

      // Update the data-liked attribute
      likeIcon.setAttribute('data-liked', response.liked_by_user);
    },
    error: function (error) {
      console.error('Error:', error);
    }
  });
}

Python Flask 路由

@app.route('/like_post', methods=['POST'])
@login_required  # Use the appropriate decorator for user authentication
def like_post():
    post_id = request.json['post_id']
    post = Post.query.get_or_404(post_id)
    existing_like = Like.query.filter_by(user=current_user, post=post).first()
    liked_by_user = existing_like is not None

    if not post:
        flash("Post does not exist", "error")
        return jsonify({'error': 'Post does not exist'})

    if existing_like:
        # User has already liked the post, so unlike it
        db.session.delete(existing_like)
        db.session.commit()
        liked_by_user = False
    else:
        # User has not liked the post, so like it
        like = Like(user=current_user, post=post)
        db.session.add(like)
        db.session.commit()
        liked_by_user = True
    
    response_data = {
        'liked_by_user': liked_by_user,
        'like_count': post.count_likes()  # Assuming you have a method to count likes
    }

    return jsonify(response_data)

我想向用户展示喜欢的状态,无论他喜欢与否,即使在重新加载页面后,也不应更改图标类。 但是现在,如果用户喜欢该帖子,则计数会根据需要递增,并且类会顺利更改,但是如果用户重新加载页面,则类会从实心变为常规,但计数很好。

如何解决这个问题? 将非常感谢您的指导。

Ajax Flask 发布 社交点赞

评论


答: 暂无答案