简体   繁体   English

使用 javascript 提交 django 表格

[英]submitting a django form using javascript

ok so have this snippet of code -好的,所以有这段代码 -

    <form id="myform" name="myform" action="." method="post">
        <a href="javascript: document.forms['myform'].submit();" name="myform">Submit
        </a>
    </form>    

i am submitting a form using an href and some javascript to my django server.我正在使用 href 和一些 javascript 向我的 django 服务器提交表单。 on the server i check the post request using the following code -在服务器上,我使用以下代码检查发布请求 -

    if 'myform' in request.POST:
        '''handle the form submition'''
        return True
    return False

this returns false.这返回错误。 any ideas why?任何想法为什么?

here is the solution i used to solve my problem - (thank you very much fosco and adam!)这是我用来解决问题的解决方案 - (非常感谢 fosco 和 adam!)

    <form id="my_form" action="." method="post">
        <a href="#" onclick="document.forms['my_form'].submit();">Call Form</a>
        <input type="checkbox" name="call_form" checked style="visibility:hidden"><br>
        <input type="submit" value="create form" style="visibility:hidden" />
    </form>`

I assume "using an href" means you click a link programatically?我假设“使用href”意味着您以编程方式单击链接? Links always send GET requests so that's why it fails.链接总是发送 GET 请求,这就是它失败的原因。 You can submit the entire form with JS using document.forms.myform.submit();您可以使用 JS 提交整个表单document.forms.myform.submit(); and that will send it with POST since that's the method you specified in the form.这将使用 POST 发送它,因为这是您在表单中指定的方法。

Are there any input fields in this form?此表单中是否有任何输入字段? You should be checking for that rather than the name of the form.您应该检查它而不是表单的名称。 The form itself is nothing, so what data is being posted?表单本身什么都不是,那么发布的是什么数据? ie a text input field named someData.即名为 someData 的文本输入字段。 if 'someData' in request.POST:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM