猿问

如何更新字段而不刷新模板

我正在第一个 Django 教程中制作投票应用程序。我看到每次投票时,页面都会刷新并转到页面顶部,我希望它只停留在原处,只更新段落标签。细节.html:


<html dir="rtl">

<h1>{{ article.title }}</h1>

<h2>{{ article.author }}</h2>

<h1>{{ article.text }}</h1>

<p>I have {{article.votes}}</p>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'main:vote' article.id %}" method="post">

{% csrf_token %}

<input type="submit" value="Vote">

</form>

</html>

views.py 中的投票函数:


def vote(request, article_id):

    article = get_object_or_404(Article, pk=article_id)

    article.votes += 1

    article.save()

    # TODO: Change it so it doesnt return new refreshed html

    return render(request, 'main/detail.html', {'article': article})


胡说叔叔
浏览 101回答 1
1回答

收到一只叮咚

你的模板应该是这样的<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>&nbsp; &nbsp; $("#vote").click(function (e) {&nbsp; &nbsp; &nbsp; e.preventDefault()&nbsp; &nbsp; &nbsp; var upvotes = $("#total_votes").html()&nbsp; &nbsp; &nbsp; var updatedUpVotes = parseInt(upvotes) + 1&nbsp; &nbsp; &nbsp; $("#total_votes").html(updatedUpVotes)&nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: 'vote/',&nbsp; &nbsp; &nbsp; &nbsp; method: "GET",&nbsp; &nbsp; &nbsp; &nbsp; data: {},&nbsp; &nbsp; &nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(data)&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function (error) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(error)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; })&nbsp; </script></html>您的视图应返回 JsonResponsefrom django.http import JsonResponsedef vote(request, article_id):&nbsp; &nbsp; article = get_object_or_404(Article, pk=article_id)&nbsp; &nbsp; article.votes += 1&nbsp; &nbsp; article.save()&nbsp; &nbsp; return jsonResponse(data = {"vote": "Voted! Thank you for the vote."})考虑到您的投票网址位于article/id/vote.
随时随地看视频慕课网APP

相关分类

Python
我要回答