我有一个简单的基于博客的网页,您可以在其中喜欢帖子,但是当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);
});
});
答案 0 :(得分:1)
在ajax .done()
函数中,您应该更改以下内容:
$('result'+post_id).html(data)
对此
$('#result'+post_id).html(data)
因为在jQuery中,您必须向#
的第一个查询中添加id
答案 1 :(得分:0)
这只是我的概念。它将为您提供有关如何使用它的想法。
您可以看到我如何将like和different与id属性相连,以便将其发布为ajax
<a class="unlike" id="unlike_{{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>
<a class="like" id="like_{{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>
在这里您可以将postid传递为post_id1,将操作传递为likelike
因此,您可以拥有类似的东西
if likeunlike == 'like':
current_user.like_post(post)
db.session.commit()
if likeunlike == 'unlike':
current_user.unlike_post(post)
这是您的ajax脚本的外观
$(document).ready(function(){
// like and unlike click
$(".like, .unlike").click(function(){
var id = this.id; // Getting Button id
var split_id = id.split("_");
var text = split_id[0];
var post_id1 = split_id[1]; // postid
// AJAX Request
$.ajax({
url: '/ur-url',
type: 'post',
data: {post_id1:post_id1,likeunlike:text},
dataType: 'html',
success: function(data){
//var likes = data['likes'];
//var unlikes = data['unlikes'];
$("#likes_"+post_id).html(data); // setting likes
$("#unlikes_"+post_id).html(data); // setting unlikes
}
});
});
});
这只是概念。 时间不在我的身边,否则我会在里面深入挖掘...谢谢