submitting a django form using javascript

别来无恙 提交于 2019-12-20 03:26:31

问题


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. 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?


回答1:


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? i.e. a text input field named someData. if 'someData' in request.POST:




回答2:


here is the solution i used to solve my problem - (thank you very much fosco and 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>`



回答3:


I assume "using an href" means you click a link programatically? Links always send GET requests so that's why it fails. You can submit the entire form with JS using document.forms.myform.submit(); and that will send it with POST since that's the method you specified in the form.



来源:https://stackoverflow.com/questions/6113292/submitting-a-django-form-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!