为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

胡说叔叔 2023-05-09 15:24:39
我正在第一个 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})
查看完整描述

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.


查看完整回答
反对 回复 2023-05-09
  • 1 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信