繁体   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