为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

犯罪嫌疑人X 2021-03-29 19:10:26
我有一个简单的基于博客的网页,您可以在其中喜欢帖子,但是当like_action发生时,它会刷新整个页面,当您已经在页面底部时,这确实很糟糕。所以基本上我只想刷新html的一部分。我读了很多有关ajax的文章,但是当尝试实现它时,效果不是很好:(@posts.route('/like/<int:post_id>/<action>', methods=['GET', 'POST'])@login_requireddef 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);          });        });
查看完整描述

2 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

在ajax.done()函数中,您应该更改以下内容:

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

到这个

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

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


查看完整回答
反对 回复 2021-04-29
  • 2 回答
  • 0 关注
  • 332 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信