簡體   English   中英

使用 JavaScript 時,Django POST 方法不起作用

[英]Django POST method is not working when using JavaScript

我正在嘗試在提交表單時顯示一個 div。 它在提交表單時顯示 div,而未提交表單。 這里使用 POST 方法。 JavaScript 用於顯示 div。

html 文件:

                    <form method="POST" name="myFirstForm" id="chform">
                        {% csrf_token %}
                        <input type="hidden" name="details_id" value="{{details.id}}"/>
                        <input type="hidden" name="details_user_id" value="{{details.user_id}}"/>
                        <input type="hidden" name="user_id" value="{{user.id}}"/>
                        <input type="submit" class="btn btn-danger" id="chat" onclick="return myFunction()" value="Chat Now">
                    </form>
                   <div class="page-content page-container" id="page-content" style="display:none"></div>

JavaScript:

<script>
 document.forms['myFirstForm'].addEventListener('submit', function(event) {
// Do something with the form's data here
this.style['display'] = 'none';
event.preventDefault();
  });
   function myFunction() {
    var x = document.getElementById("page-content");
    if (x.style.display === "none") {
      x.style.display = "block";
    } else {
      x.style.display = "none";
    }
  }

</script>

視圖.py:

    if request.method=='POST':
        jid = request.POST.get('details_id')
        print(jid)
        cjid = request.POST.get('details_user_id')
        print(cjid)
        userid = request.POST.get('user_id')
        print(userid)

如果我不想顯示 div 並刪除 JavaScript 代碼,POST 方法有效。有人可以提出解決此問題的解決方案嗎?

您是否考慮過異步 JavaScript 和 XML (AJAX)? 聽起來你想要異步 JS 功能(或者我沒有正確理解)。

因此,在您的提交按鈕中,您將使其調用 AJAX function,如下所示:

<button type="submit" id="chat" data-url="{% url 'url_to_your_view_handling_the_post' %}" value="Chat Now"></button>

然后你的onclick function:

$(document).on('click', '#chat', function (e) {

    $.ajax({
        type: 'POST',
        url: $(this).data('url'),
        data: {
            // add any other HTML data attributes in this dictionary
            csrfmiddlewaretoken: getCookie('csrftoken'),
        },
        success: function (json_response) {
            // Successful AJAX response handling routine here
            // Display your div
            var x = document.getElementById("page-content");
            if (x.style.display === "none") {
                x.style.display = "block";
            }
            else {
                x.style.display = "none";
            }
        },
        error: function (xhr, errmsg, err) { }
    });
})

因此,您在按鈕中定義的 url url_to_your_view_handling_the_post的視圖將處理 POST 方法並返回 JSON 響應以及您想要的任何數據。 如果返回成功,則運行 AJAX function 中的成功例程。

發送 csrf 令牌並不是非常簡單,我建議您參閱此線程以了解有關getCookie('csrftoken') function 的更多信息。

注意:這是 AJAX 的 jquery 實現,因此您還需要在模板中包含 jquery。

如果你想提交表單,那么你不應該調用event.preventDefault(); . 這基本上告訴 js 捕獲submit事件並阻止事件的默認行為,即在您的情況下提交表單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM