我的视图中有一个带有单个隐藏提交按钮的表单。我想在页面加载时提交表单。但是,我在Javascript中做的任何提交都给了我这个错误:
无法获取财产'提交'未定义或空引用
这是我的代码:
PrintApplication.cshtml
@using (Html.BeginForm("PrintApplications", "Admin", FormMethod.Post, new { @id = "PrintApplications", @class = "form-horizontal ", @commandname = "ModelContract", @target = "_blank" }))
{
<input id="btnPrintApplications" type="submit" class="btn btn-primary" value="PrintApplications" name="submit" style="visibility: hidden" />
}
<script>
document.onreadystatechange = function () {
document.form.submit();
}
</script>
代替document.form.submit,我也试过
var form = document.getElementById("PrintApplications");
form.submit();
document.forms["PrintApplications"].submit();
this.form.submit();
和其他变体(例如,在表单名称前面加上#)
我的代码出了什么问题。有没有其他方法可以自动提交页面(没有用户点击任何按钮)?
编辑:这是我的原始代码。它没有在IE中工作,这是我解决问题的原因。没有错误,但表格没有提交。这虽然在Chrome中运行良好。
$(document).ready(function () {
$("#btnPrintApplications").click();
});
编辑2:这是我使用@barry帖子中的代码开始工作的代码
@using (Html.BeginForm("PrintApplications", "Admin", FormMethod.Post, new { @id = "PrintApplications", @class = "form-horizontal ", @commandname = "ModelContract", @target = "_blank" }))
{
@*<input id="btnPrintApplications" type="submit" class="btn btn-primary" value="PrintApplications" name="submit" style="visibility: hidden" />*@
<div>
If applications do not appear in a separate tab or window, please click the button below.
</div>
<input id="btnPrintApplications" type="submit" class="btn btn-primary" value="Print Applications" name="print" />
}
<script>
mySubmitButton = document.getElementById("btnPrintApplications");
mySubmitButton.click();
</script>
编辑3:这里使用@ chris-pratt中的示例编写代码。
@using (Html.BeginForm("PrintApplications", "Admin", FormMethod.Post, new { @id = "PrintApplications", @class = "form-horizontal ", @commandname = "ModelContract", @target = "_blank" }))
{
<div>
If applications do not appear in a separate tab or window, please click the button below.
</div>
<input id="btnPrintApplications" type="submit" class="btn btn-primary" value="Print Applications" name="print" />
}
<script>
window.onload = function () {
document.forms['PrintApplications'].submit();
}
</script>
答案 0 :(得分:1)
以下简单的HTML文档完全符合您的要求:
<html>
<body>
<form id="Test" action="http://google.com" target="_blank">
<input type="hidden" name="q" value="test" />
</form>
<script>
window.onload = function () {
document.forms['Test'].submit();
}
</script>
</body>
</html>
我最初使用document.onreadystatechange
,这也有用,但注意到IE 11显然会两次触发该事件,导致两个弹出窗口。而不管。也许通过向后工作,你可以找到你的问题。
答案 1 :(得分:1)
试试这个
mySubmitButton = document.getElementById("PerfSubmit");
mySubmitButton.click();
使用以下代码,表单将被提交
$('form')[0].submit();
或
mySubmitButton.trigger("click");