Django + Ajax:发布后更新div

时间:2015-08-05 11:15:18

标签: ajax django

我是Ajax和Django的新手。我有一个类似Ajax的按钮,可以在我的数据库中添加“喜欢”。除了按钮,我的模板还会显示喜欢的总数。该按钮有效,但我无法弄清楚如何更新“like-count”div,因为调用{{ post.likes.count }}会显示旧结果。我猜这是由于缓存?为了解决这个问题,我在视图中声明了一个like_count变量,然后在喜欢时添加+ = 1。

如何在模板中使{{ like_count }}正常工作?使用

return render(request, 'app/blog.html', {'like_count': like_count})

将我发送到空白页而不是更新div。

查看:

@login_required
def like(request):
    if request.is_ajax():
        user = request.user
        post_id = request.POST.get('post', None)
        content = ContentType.objects.get_for_model(Post)
        like_count = Like.objects.filter(content_type=content, object_id=post_id).count()

        if Like.objects.filter(user=user, content_type=content, object_id=post_id).exists():
            # remove like
            Like.objects.filter(user=user, content_type=content, object_id=post_id).delete()
            like_count -=1

        else:
            # add a new like
            Like.objects.create(user=user, content_type=content, object_id=post_id)
            like_count +=1

    return HttpResponse()
    return render(request, 'app/blog.html', {'like_count': like_count}) 

模板:

<div id="like-count">Like {{ post.likes.count }}</div>
<form method="post" action="{% url 'like' %}" id="like-form">
         {% csrf_token %}
         <input type="hidden" id="post_id" name="post" class="hidden_id" value="{{ post.pk }}" />
  <input type="hidden" id="user_id" name="user" class="hidden_id" value="{{ user.pk }}" />
  <button class="btn">Like</button>
         </form>

<script type="text/javascript">
    var frm{{ post.id }} = $('#like-form');
    frm{{ like.id }}.submit(function (ev) {
        $.ajax({
            type: frm{{ post.id }}.attr('method'),
            url: frm{{ post.id }}.attr('action'),
            data: frm{{ post.id }}.serialize(),
            success: function (data) {
                document.getElementById("like-count").innerHTML = {{ like_count }};
            }
        });

        ev.preventDefault();
    });
</script>

1 个答案:

答案 0 :(得分:0)

假设Django 1.7 +

def like(request):
    if request.is_ajax():
      ... make sure that this is the return that gets used
    return JsonResponse({'like_count':someVar})

在客户端上......类似于:

  $.ajax({
            ...
            success: function(response) {
                document.getElementById('like-count').innerHTML = response['like_count'];
            }
        })