Django使用ajax为自定义django按钮

时间:2016-01-22 21:19:23

标签: javascript html ajax django

所以我试图用ajax创建我自己的自定义按钮但是有一个问题,当我按下类似按钮时我应该重新加载页面以便查看我的upvote。我想在不重新加载页面的情况下这样做。

这是代码:

article.html

{% block content %}
<div>
    {% for a in article %}
    [... unrelated html ...]

    <p><input type="button" class="like" id="{{ a.id }}" value="Like" /></p>
    <p id="count{{ a.id }}">{{ a.total_likes }}</p>
    </div>
    {% endfor %}

</div>
<script>

$('.like').click(function(){

      $.ajax({
               type: "POST",
               url: "{% url 'like_button' %}",
               data: {'pk': $(this).attr('id'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      var pk = $(this).attr('id');
                      $('#count' + pk).html(response.likes_count) #change the html when success. response.likes_count is connected to python, it indicates the number of counts on the query.
                },
               error: function(rs, e) {
                      alert(rs.responseText);
               }
          });
    })

</script>
{% endblock %}

为了解决这个问题,我该怎么做?

1 个答案:

答案 0 :(得分:2)

内部success回调this并未指向DOM元素

$('.like').click(function(){
  var pk = $(this).attr('id'); // Get your id here
  // Whole ajax stuff
})