我正在尝试学习 django 以及更多知识。 计算磁带中每个帖子的点赞数时遇到问题。问题是我无法获取帖子的 ID。 如果我刷新页面,点赞数会发生变化。但用ajax改变它是真正的问题。 请解释一下,如果单击“喜欢”按钮,如何对磁带中的每个帖子进行更改“喜欢”计数。
Ajax 代码。
{% block jquery %}
function updatePostLikesCount(){
var postlikescount = $(".post-likes-count")
$.ajax({
type: "GET",
url: "/like_post/{{ post.id }}/post_likes_count/",
success: function(data){
postlikescount.html(data.count);
},
error: function(response, error){
}
})
}
$(".post-like").click(function(event){
var img = $(this);
event.preventDefault();
$.ajax({
url: img.parent().attr('href'),
success: function(){
updatePostLikesCount();
},
error: function(response, error){
}
})
});
{% endblock %}
这是帖子的磁带。
{% for post in tape %}
...
{{ post.text }}
...
<a href="/like_post/{{ post.id }}/">
<img class="post-like" src="{% static "" %}"/>
</a>
<span class="post-likes-count" >
{{ post.like.liked_users.count }}
</span>
{% endfor %}
这是一个计算帖子点赞数的 View
def post_likes_count(request, post_id, *args, **kwargs):
if request.is_ajax():
like = Like.objects.get(post_id=post_id)
if like.liked_users.count == None:
count = 0
else:
count = LikeTimestamp.objects.filter(like_id=like.id).count()
return JsonResponse({
'count': count,
})
else:
raise Http404
否则我尝试用“likes”重新加载页面元素,但失败了:-)
最佳答案
更新:
{% block jquery %}
function updatePostLikesCount(postlikescount){
$.ajax({
type: "GET",
url: "/like_post/"+postlikescount.data().id+"/post_likes_count/",
success: function(data){
alert('class is '+postlikescount.parent().find('.post-likes-count').attr('class'));
postlikescount.parent().find('.post-likes-count').html(data.count).show();
alert('likes count '+data.count);
},
error: function(response, error){
}
})
}
$(".post-like").click(function(event){
var img = $(this);
event.preventDefault();
$.ajax({
url: img.parent().attr('href'),
success: function(){
var like = img.parent();
updatePostLikesCount(like);
},
error: function(response, error){
}
})
});
{% endblock %}
像这样稍微更改 View (添加数据ID):
{% for post in tape %}
...
{{ post.text }}
...
<a href="/like_post/{{ post.id }}/" data-id="{{post.id}}">
<img class="post-like" src="{% static "" %}"/>
</a>
<span class="post-likes-count" {% if post.like.liked_users.count == 0 %}style="display:none;"{% endif %}>
{{ post.like.liked_users.count }}
</span>
{% endfor %}
关于javascript - 单击喜欢按钮时,无法使用 ajax 更改磁带中帖子的喜欢数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38040354/