javascript 如何使用jQuery提交表单然后重新加载页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13811100/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:50:29  来源:igfitidea点击:

How to use jQuery to submit a form and then reload the page

javascriptjquery

提问by Webjedi

I'm trying to figure out if this is possible.

我想弄清楚这是否可能。

I have Page-A that has Form-Foo with an action to Bar in a new window.

我有一个带有 Form-Foo 的 Page-A,在新窗口中对 Bar 执行操作。

Upon clicking submit, I'd like the form to submit AND Page-A to reload.

单击提交后,我希望表单提交和页面 A 重新加载。

So far I can only get one or the other to work...any pointers would be appreciated.

到目前为止,我只能让一个或另一个工作......任何指针将不胜感激。

In addition to DudeSolutions solution...I tried this:

除了 DudeSolutions 解决方案......我试过这个:

$(document).ready(function() {
    $('#foo').submit(function() {
        $.post('bar.asp', $(#foo).serialize(), function(data) {

                window.location.reload();

        });

    });
});

Same results...I can get the form to submit and a new tab opens...but Page-A does not reload.

相同的结果...我可以提交表单并打开一个新选项卡...但页面 A 不会重新加载。

回答by adeneo

If you intend to submit the form and reload the page, that would be the default behaviour, and only the url in the action attribute is incorrect. If so just change the URL, no need for ajax if a new pageload is intended anyway :

如果您打算提交表单并重新加载页面,这将是默认行为,并且只有 action 属性中的 url 不正确。如果是这样,只需更改 URL,如果打算加载新页面,则不需要 ajax:

$(function() {
    $('#Form-Foo').attr('action', 'Page-A url');
});

or:

或者:

$(function() {
    $('#foo').on('submit', function(e) {
          e.preventDefault();
          setTimeout(function() {
               window.location.reload();
          },0);
          this.submit();
    });
});

Just queueing the reload should be enough to wait until after the form is sent to reload the page, but as most browsers stop the timeout when you leave the browser tab, it won't really reload until you go back to that tab, but that should be unnoticeable.

只是排队重新加载应该足以等到发送表单后重新加载页面,但是由于大多数浏览器在您离开浏览器选项卡时停止超时,因此在您返回该选项卡之前它不会真正重新加载,但是应该是不明显的。

回答by FredTheWebGuy

Here's an idea:

这是一个想法:

  <script type="text/javascript">
    $("#my_form").submit(function() {
      $.ajax({
        type: "POST",
        url: "/path/to/post/handler/",
        data: $("#my_form").serializeArray(),
        success: function() {
    top.reload();
        }
        });
    return false;
});</script>