我有一个简单的基于博客的网页,您可以在其中喜欢帖子,但是当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);
});
});
慕少森
相关分类