【问题标题】:Django Using ajax for a custom django like buttonDjango 将 ajax 用于自定义 django 类按钮
【发布时间】:2016-01-22 21:19:23
【问题描述】:

所以我正在尝试使用 ajax 创建自己的自定义点赞按钮,但有一个问题,当我按下点赞按钮时,我应该重新加载页面以查看我的投票。我想在不重新加载页面的情况下这样做。

代码如下:

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 %}

我应该怎么做才能解决这个问题?

【问题讨论】:

    标签: javascript html ajax django


    【解决方案1】:

    success 内部回调 this 不指向 DOM 元素

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-27
      • 2015-12-19
      • 2021-12-12
      • 2014-06-08
      • 1970-01-01
      • 2011-04-25
      • 2014-08-19
      • 2013-05-22
      相关资源
      最近更新 更多