我有一个简单的基于博客的网页,你可以喜欢的文章,但当喜欢的动作发生时,它刷新了整个网页,这是非常糟糕的,当你已经在底部的网页。所以基本上我只想刷新html的一部分。你知道吗
我读了很多关于ajax的书,但是当a试图实现它时,它并没有很好地工作:(
@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);
});
});
这只是我的想法。它会让你知道如何处理它。你知道吗
您可以看到我是如何将like和inspect附加到id属性的,以便我可以将其作为ajax发布
在这里,您可以将posted作为post\u id1传递,并像这样执行操作
因此你可以有类似
下面是ajax脚本的样子
这只是个概念。 时间不在我身边,否则我会深入研究…谢谢
在ajax
.done()
函数中,您应该更改以下内容:到这个
因为在jQuery中,必须将
#
添加到id
的第一个查询中相关问题 更多 >
编程相关推荐