我有一個(gè)簡(jiǎn)單的基于博客的網(wǎng)頁(yè),您可以在其中喜歡帖子,但是當(dāng)like_action發(fā)生時(shí),它會(huì)刷新整個(gè)頁(yè)面,當(dāng)您已經(jīng)在頁(yè)面底部時(shí),這確實(shí)很糟糕。所以基本上我只想刷新html的一部分。我讀了很多有關(guān)ajax的文章,但是當(dāng)嘗試實(shí)現(xiàn)它時(shí),效果不是很好:(@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); }); });
用戶(hù)喜歡帖子時(shí)如何動(dòng)態(tài)更新Flask模板?
犯罪嫌疑人X
2021-03-29 19:10:26