1 回答

TA贡献1821条经验 获得超4个赞
你的模板应该是这样的
<html dir="rtl">
<h1>{{ article.title }}</h1>
<h2>{{ article.author }}</h2>
<h1>{{ article.text }}</h1>
<p>I have <span id="total_votes">{{article.votes}}</span> votes.</p>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<button id="vote">Vote</button>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$("#vote").click(function (e) {
e.preventDefault()
var upvotes = $("#total_votes").html()
var updatedUpVotes = parseInt(upvotes) + 1
$("#total_votes").html(updatedUpVotes)
$.ajax({
url: 'vote/',
method: "GET",
data: {},
success: function (data) {
console.log(data)
},
error: function (error) {
console.log(error)
}
})
})
</script>
</html>
您的视图应返回 JsonResponse
from django.http import JsonResponse
def vote(request, article_id):
article = get_object_or_404(Article, pk=article_id)
article.votes += 1
article.save()
return jsonResponse(data = {"vote": "Voted! Thank you for the vote."})
考虑到您的投票网址位于article/id/vote.
添加回答
举报