[英]Django Using ajax for a custom django like button
So I am trying to create my own custom like button with ajax but there is one problem, when I press the like button I should reload the page in order to see my upvote. 所以我试图用ajax创建自己的自定义“赞”按钮,但是有一个问题,当我按下“赞”按钮时,我应该重新加载页面以查看我的赞誉。 I want to do it without reloading the page. 我想这样做而无需重新加载页面。
here is the code: 这是代码:
article.html 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 %}
What should I do in order to reslove this issue? 我该怎么做才能解决这个问题?
Inside success
callback this
doesn't point to DOM element 在success
回调中, this
并不指向DOM元素
$('.like').click(function(){
var pk = $(this).attr('id'); // Get your id here
// Whole ajax stuff
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.