Javascript 在和 onload 函数中提交 HTML 表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6209079/
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
Submitting a HTML form in and onload function
提问by Adam Right
I want send a form as soon as the page is loaded. All variables in the form are written dynamically and there is no button for submitting.
我想在页面加载后立即发送表单。表单中的所有变量都是动态写入的,没有提交按钮。
Does following JS script work in all browsers ?
以下 JS 脚本是否适用于所有浏览器?
<script type='text/javascript'> window.onload = function(){ window.document.forms[0].submit(); }; </script>
I doubt window.onload
will work in all without any problems.
我怀疑window.onload
是否会在没有任何问题的情况下工作。
Thanks in advance...
提前致谢...
回答by Ken Pespisa
If you're worried about compatibility in all browsers, how about using jQuery's ready function?
如果你担心在所有浏览器中的兼容性,使用 jQuery 的 ready 功能怎么样?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
window.document.forms[0].submit();
});
</script>
回答by Dan Atkinson
Whilst I would agree that Ken's answeris perfectly acceptable, I don't believe it is correct to include a full-fat JS library just for its .ready()
functionality.
虽然我同意Ken 的答案是完全可以接受的,但我认为仅仅为了其.ready()
功能而包含一个全脂 JS 库是不正确的。
For what it's worth, I'd recommend docReady. The size of docReady is 322 bytes gzipped (548 bytes uncompressed).
对于它的价值,我推荐docReady。docReady 的大小为 322 字节 gzip(未压缩 548 字节)。
docReady(function() {
window.document.forms[0].submit();
});
I love jQuery, and I'd even say that there's not much of a perf impact in Ken's answer because it's likely that, if you're using the Google CDN, you've probably already downloaded it during your time on that site or others. But still, it's an unnecessary overhead on what should be a simple page IMO.
我喜欢 jQuery,我什至会说 Ken 的回答对性能没有太大影响,因为很可能,如果您使用的是 Google CDN,您可能已经在该网站或其他网站上下载了它. 但是,对于应该是简单页面 IMO 的内容,这仍然是不必要的开销。
回答by Battle_707
Don't use the window.onload (I mean, you can, but is easier/ more logical to do it differently). What you should do is print the form in a hidden div tag, assign an id to the submit button and then use javascript to 'click' it. Here is an example:
不要使用 window.onload (我的意思是,你可以,但更容易/更合乎逻辑地以不同方式执行)。您应该做的是在隐藏的 div 标签中打印表单,为提交按钮分配一个 id,然后使用 javascript 来“单击”它。下面是一个例子:
<div style="display: hidden;">
<form action="page/site" method="get/post">
<input type="hidden" name="name" value="value" />
<input type="submit" id="formButton" />
</form>
<script language="javascript">
document.getElementById("formButton").click();
</script>
</div>
I hope that helps.
我希望这有帮助。