页面加载jQuery表单提交不起作用

时间:2019-03-13 22:49:57

标签: javascript jquery post pageload

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
                submitForm($("#login-user-one"));
            });

            function submitForm(form) {
                console.log($(form).attr("method"));
                $(form).submit();
            };
        </script>
    </head>
    <body>
        <form id="login-user-one" name="login" method="POST" action="/test.html">
            <input name="userid" tabindex="1" value="MyUser">
            <input name="pass" type="password" tabindex="2" value="MyPass">
            <input type="submit" name="submit" value="1" tabindex="3">
        </form>
    </body>
</html>

我不知道为什么上述方法不起作用。日志向我显示了POST的值,但不会提交。控制台中没有错误。

JS小提琴:https://jsfiddle.net/t48hk9qx/

2 个答案:

答案 0 :(得分:1)

删除名称=在您的输入中提交将解决问题。 https://codesandbox.io/s/64kl2l3wvk。我认为是因为form.submit函数被名称为commit的输入替换。

答案 1 :(得分:1)

好吧,这对我来说是新的。

因为您的表单具有一个名为name="submit"的命名元素,所以该元素引用将替换HTMLFormElement.prototype.submit()函数。

documentation ...

  

已命名的输入作为属性添加到其所有者表单实例,并且如果它们共享相同的名称,则可以覆盖本机属性(例如,具有名为action的输入的表单将具有其action属性返回输入而不是表单的action HTML属性)。

当以编程方式通过类似方式提交表单时,jQuery尝试执行该功能

if (typeof element.submit === 'function') {
  element.submit()
}

但是在您的情况下,element.submitHTMLInputElement

快速简便的解决方案,重命名您的 submit 元素,或者在单按钮表单中更为常见,只需删除name属性即可。


如果您必须,将提交按钮保持为“ submit” ,这似乎可行

function submitForm(form) {
  // note, "form" is already a jQuery object
  console.log(form.attr("method"));

  HTMLFormElement.prototype.submit.call(form[0])
}
相关问题