使用 Javascript 提交表单不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18902922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit form with Javascript doesn't work
提问by peastman
I have a simple form for uploading a file. If I use an ordinary submit button, everything works as expected:
我有一个用于上传文件的简单表单。如果我使用普通的提交按钮,一切都会按预期进行:
<form id="mainform" method="post" action="/" enctype="multipart/form-data">
...
<input type="submit" id="submit" value="Analyze File"/>
</form>
But if I change it to an ordinary button and use Javascript to submit the form, nothing happens:
但是,如果我将其更改为普通按钮并使用 Javascript 提交表单,则没有任何反应:
<input type="button" id="submit" value="Analyze File" onclick="document.getElementById('mainform').submit()"/>
I verified that the onclick handler really is getting called, and looking up the form works correctly. For example, if I change it to onclick="alert(document.getElementById('mainform').action)"
, the alert comes up as expected and shows the target URL of the form. But for some reason, the call to submit() simply doesn't submit the form.
我验证了 onclick 处理程序确实被调用了,并且查找表单工作正常。例如,如果我将其更改为onclick="alert(document.getElementById('mainform').action)"
,警报会按预期出现并显示表单的目标 URL。但是出于某种原因,对 submit() 的调用根本没有提交表单。
回答by Joe Enos
The issue is your submit
button. Its id is submit
, which means that document.getElementById("mainform").submit
represents the button with ID of submit
, not the submit
function.
问题是你的submit
按钮。它的 id 是submit
,document.getElementById("mainform").submit
表示代表的是 ID 为 的按钮submit
,而不是submit
函数。
You just need to change the ID for that button, and you're all good.
您只需要更改该按钮的 ID,就可以了。
回答by Jonathan Lonowski
You have a naming conflict between the .submit()
method and the:
您在.submit()
方法和以下内容之间存在命名冲突:
<input type="submit" id="submit" value="Analyze File"/>
By having that id
, a reference to it is being assigned to the submit
property of the <form>
, which replaces the method.
通过拥有 that id
,对它的引用被分配给 的submit
属性,该属性<form>
替换了该方法。
If you rename the <input>
, you should be able to .submit()
as expected:
如果您重命名<input>
,您应该能够.submit()
按预期进行:
<input type="submit" id="mainform_submit" value="Analyze File"/>