点击按钮时,无法更改带有ajax的磁带中的post数量
我正在努力学习django和更多。 计算磁带中每个post的喜欢数量都有问题。 问题是我无法获得post的身份。 如果我刷新页面,喜欢的数量会发生变化。 但是用ajax改变它是真正的问题。 如果点击按钮,请解释我如何更改磁带中的每个post。
Ajax代码。
{% block jquery %} function updatePostLikesCount(){ var postlikescount = $(".post-likes-count") $.ajax({ type: "GET", url: "https://stackoverflow.com/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 %}
这是post的磁带。
{% for post in tape %} ... {{ post.text }} ... {{ post.like.liked_users.count }} {% endfor %}
这是一个计算post喜欢的视图
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
另外,我试图用喜欢重新加载一个页面元素,但被击败:-)
更新:
{% 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 %}
像这样稍微改变视图(添加data-id):
{% for post in tape %} ... {{ post.text }} ... {{ post.like.liked_users.count }} {% endfor %}
一些方法来改善这一点。
首先……你总是希望计数的html存在,并且只有在没有喜欢或显示为零的情况下才应该隐藏它。 否则你需要在第一次投票时添加带有javascript的html
下一个
var postlikescount = $(".post-likes-count");
这将包括页面中该类的所有元素….而不是您单击按钮时所需的特定元素。
相反,您可以将您想要的那个传递给updatePostLikesCount()
作为参数
更改
function updatePostLikesCount(){ var postlikescount = $(".post-likes-count");
至
function updatePostLikesCount(postlikescount){
并在单击处理程序修改,所以我们传入适当的元素
success: function() { // which count element var $countElement = img.next(); // pass to function updatePostLikesCount($countElement); }