javascript - 当用户喜欢帖子时如何动态更新 Flask 模板?

标签 javascript python ajax flask

我有一个简单的基于博客的网页,您可以在其中喜欢帖子,但是当 like_action 发生时,它会刷新整个页面,当您已经位于页面底部时,这真的很糟糕。所以基本上我只想刷新 html 的一部分。

我读了很多关于 ajax 的内容,但是当尝试实现它时效果并不好:(

@posts.route('/like/<int:post_id>/<action>', methods=['GET', 'POST'])
@login_required
def like_action(post_id, action):
    post = Post.query.filter_by(id=post_id).first_or_404()
    if action == 'like':
        current_user.like_post(post)
        db.session.commit()
    if action == 'unlike':
        current_user.unlike_post(post)
        db.session.commit()
    return render_template('section.html', post = post)
<div class="likes" id="result{{post.id}}">
  <hr>
  {% if current_user.is_authenticated %}
    {% if current_user.has_liked_post(post) %}
      <a class="updateButton" post_id="{{post.id}}" href="{{ url_for('posts.like_action', post_id=post.id, action='unlike') }}"><img src="{{url_for('static', filename='heart-filled.png')}}" style="width:5%; height:5%;"></a>
    {% else %}
      <a class="updateButton" post_id="{{post.id}}" href="{{ url_for('posts.like_action', post_id=post.id, action='like') }}"><img src="{{url_for('static', filename='heart-no-fill.png')}}" style="width:5%; height:5%;"></a>
    {% endif %}
  {% else %}
    <img src="{{url_for('static', filename='heart-no-fill.png')}}" style="width:5%; height:5%;">
  {% endif %}
  <small>{{post.likes.count()}}</small>
</div>

      $(document).ready(function(){

        $(document).on('click','.updateButton', function(){

          var post_id = $(this).attr('post_id');

          req = $.ajax({
            url:'/like/<int:post_id>/<action>'
            type:'POST'
            data: {id:post_id}
          });

          req.done(function(data){
            $('result'+post_id).html(data);
          });

        });

最佳答案

在你的 ajax .done() 函数中你应该改变这个:

$('result'+post_id).html(data)

到这个

$('#result'+post_id).html(data)

因为在 jQuery 中,您必须将 # 添加到 id 的第一个查询中

关于javascript - 当用户喜欢帖子时如何动态更新 Flask 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667709/

相关文章:

javascript - React JS Redux 登录后加载数据

javascript - 当div显示:none时停止setInterval

python - OpenGL - 一些相交和一些非相交多边形的曲面分割

python - 在 Python 中使用 urlopen() 防止 "hidden"重定向

javascript - 带有用户输入的 API 查询

javascript - 将列表项拖到新的相对位置并保存到数据库

javascript - 在 Chrome 调试器中将 DOM 元素作为对象查看

python - 当枚举类字段更改时引发 ValueError

jquery - TypeError : $. ajax(...) 不是函数?

javascript - 如何使用 jquery 展开/折叠 (+/-) 嵌套动态列表