亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

胡說叔叔 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條經驗 獲得超5個贊

你的模板應該是這樣的


<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 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號