[英]Django Using ajax for a custom django like button
所以我試圖用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 %}
我該怎么做才能解決這個問題?
在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.