如何在表单提交到_blank后刷新表单页面

How can I refresh a form page after the form submits to _blank?

本文关键字:刷新 表单 blank 表单提交      更新时间:2023-09-26

我有一个针对_blank的HTML表单。我希望表单所在的页面在提交后重新加载。

所以这里有一些示例标记:

<form method="POST" action="result.php" target="_blank">
    <label for="name">Name:</label>
    <input type="text" name="name" />
    <label for="email">Email:</label>
    <input type="email" name="email" />
    <input type="submit" value="submit" />
</form>

因此,当您提交此表单时,它将POST在新窗口或选项卡中result.php。这将使表单页面保持原样。我希望表单页面重新加载,或至少重置所有字段。

我已经尝试了<form onsubmit="location.reload()"...onsubmit="window.location.reload()"但没有任何改变。

有什么建议吗?

(请不要查询)

不知道为什么window.location.reload()不起作用。 我认为应该。 但是,这似乎确实有效:

onsubmit="setTimeout(function () { window.location.reload(); }, 10)"

有两种方法可以做到这一点,一种你可能不想听到。

第一:

在表单 init 标签中,如果您设置action=""则表单将提交到同一页面(提交到自身)。

<form action="" method="post">

这允许您将服务器端代码添加到页面顶部,如下所示(例如,使用 PHP):

<?php
    If (empty($_POST)===false) {
        //server side scripting to handle the submitted form
    }else{
?>
    //HTML to create/show the page with form for user input
<?php
    //Close the if statement
    }
?>

第二:

使用AJAX

(javascript或jQuery)"提交"表单,然后在AJAX函数的回调中继续对页面进行任何更改,包括重定向到新页面。

接受的答案并没有为我带来预期的结果。

Accepted answer:
onsubmit="setTimeout(function () { window.location.reload(); }, 10)"

将接受的答案从提交更改为点击确实解决了我的问题;

Worked for me:
onclick="setTimeout(function () { window.location.reload(); }, 3)"

可能会有不希望的结果,或者这可能不是首选,但它的表现符合我的预期。

如果将

回调传递给 onsubmit 事件属性,它应该可以工作。例如

(传统的匿名功能)

onsubmit="function() {location.reload()}"

(箭头功能)

onsubmit="() => location.reload()"
location.refresh(true);

会有所帮助