0
所以我想創建自己喜歡的按鈕與ajax,但有一個問題,當我按下按鈕我應該重新加載頁面,以便看到我的upvote。我想在不重新加載頁面的情況下執行此操作。Django使用ajax自定義Django like按鈕
這裏是代碼:
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 %}
我應該以reslove這個問題呢?