Javascript 单击“返回”按钮后防止重新提交表单

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

Prevent resubmit form after click "back" button

phpjavascriptmysql

提问by zac1987

I have 2 pages :

page1.php :
- has a form with text box and a "submit" button. Eg : <form name="frm_register" action="page1.php" method="post">

- php and mysql code to store the value of textbox to database. Javascript will redirect the page to php2.phpafter the value is submitted to database. Eg :

我有 2 页:

page1.php :
- 有一个带有文本框和“提交”按钮的表单。例如:<form name="frm_register" action="page1.php" method="post">

- 用于将文本框的值存储到数据库的 php 和 mysql 代码。将php2.php值提交到数据库后,Javascript 会将页面重定向到。例如:

$query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
$result = mysql_query($query, $connection);
echo '<script language="javascript">window.location="page2.php";</script>';

page2.php
- mysql retrieve the data from database and display on this page.

page2.php
- mysql 从数据库中检索数据并显示在此页面上。

Problem :When I press "back" button, the browser will pop up a warning message saying that the form will be resubmit. How to prevent resubmit the form when click "back" button? Is it I need to clear the cache of page1.php? How to do it with php or javascript or ajax?

问题:当我按下“返回”按钮时,浏览器会弹出一个警告信息,提示表单将被重新提交。单击“返回”按钮时如何防止重新提交表单?是否需要清除page1.php 的缓存?如何使用 php 或 javascript 或 ajax 来实现?



Update 1 :更新 1:感谢您将 javascript 替换window.location="page2.php"window.location="page2.php"为 php的答案header('Location: home2.php');header('Location: home2.php');。它解决了 80% 的问题。其余 20% 的问题如下所示:

    if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
                if (($username != "") AND ($username != $_SESSION[username])){
                    $_SESSION['servertime'] = $servertime; 
                    $_SESSION['username'] = $username;
                    $query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
                    $result = mysql_query($query20, $connection);
                    header('Location: page2.php');
                    exit;
                } else {
                    echo "same name"; //problem here
                }
            }else{
                echo "submit multiple data too fast"; //problem here too.
            }
   }

The problem happen when do the following steps :
1) User submit data successfully, jump to page2.php view records.
2) User click "back" button, jump back to page1.php.
3) User submit data fail, stay on page1.php. (because too fast or same name)
4) User submit data successful, jump to page2.php view records.
5) User click "back" button, but browser shows warning message "form will be resubmited".

执行以下步骤时出现问题:
1)用户提交数据成功,跳转到page2.php查看记录。
2) 用户点击“返回”按钮,跳转回page1.php。
3) 用户提交数据失败,停留在page1.php。(因为太快或者同名)
4)用户提交数据成功,跳转到page2.php查看记录。
5) 用户单击“返回”按钮,但浏览器显示警告消息“表单将重新提交”。

The problem is because of Step 3. Step 3 didn't run header('Location: page2.php');, didn't jump to page2.php. So it cause Step 5 show the warning message. How to fix this problem?

问题是因为第3步。第3步没有运行header('Location: page2.php');,没有跳转到page2.php。所以它会导致步骤 5 显示警告消息。如何解决这个问题?



Update 2 :更新 2:我已经找到了解决 20% 问题的解决方案,它运行良好。我session['error123']session['error123']用来决定是否要显示错误消息“同名”。session['error123']session['error123']如果成功提交数据到数据库或者成功跳转到page2.php,我就会杀死。我还使用header('Location: page1.php');header('Location: page1.php');重定向到自己的页面(同一页面)以使页面忘记之前提交的表单。代码示例:

if ($_SESSION['error123'] == "toofast"){
    echo $_SESSION['error123'] ;
}elseif ($_SESSION['error123'] == "samename"){
    echo $_SESSION['error123'] ;
}

if (strtotime($_SESSION['servertime']) < time()-3){ //10800 = 3 hours 3600 = 1 hour
                if (($username != "") AND ($username != $_SESSION['username'])){
                    $_SESSION['username'] = $username;
                    $query = "INSERT INTO traceuser (username) VALUES ('{$username}')";
                    $result = mysql_query($query20, $connection);
                    $_SESSION['error123'] = "aa";
                    header('Location: http://localhost/plekz/page2.php');
                    exit;
                } else {
                    $_SESSION['error123'] = "samename";
                    header('Location: http://localhost/plekz/page1.php');
                    exit;
                }
            }else{
                $_SESSION['error123'] = "toofast";
                header('Location: http://localhost/plekz/page1.php');
                    exit;
            }
        }
    }

Note : You need to buffer the output by <?php ob_start();?>because $_SESSION cannot put before header(). Buffer will stop all output including session, let header() send the output first.

注意:您需要缓冲输出,<?php ob_start();?>因为 $_SESSION 不能放在 header() 之前。缓冲区将停止包括会话在内的所有输出,让 header() 首先发送输出。

采纳答案by Ben Swinburne

Rather than

而不是

echo '<script language="javascript">window.location="page2.php";</script>';

echo '<script language="javascript">window.location="page2.php";</script>';

you should use the header() function to redirect your user after the submission.

您应该使用 header() 函数在提交后重定向您的用户。

So in psuedo code,

所以在伪代码中,

click submit on page.php action page1.php page1.php submits data to database calls

点击提交 page.php 动作 page1.php page1.php 提交数据到数据库调用

header('Location: http://example.com/page2.php');

This should prevent your clicking back problem

这应该可以防止您点击回退问题

回答by hakre

You can prevent the re-submission by implementing the Post-Redirect-Get (PRG Pattern).

您可以通过实施Post-Redirect-Get (PRG Pattern)来防止重新提交。

Could be just a one-line if you've got the http_redirectfunction:

如果你有这个http_redirect功能,可能只是一行:

http_redirect("page2.php");

Instead of your javascript echo.

而不是你的 javascript 回声。

If not, that are two lines:

如果没有,那是两行:

header("Location: http://example.com/page2.php");
exit;

Replace example.comwith site's your hostname.

替换example.com为站点的主机名。

Related: Back button re-submit form data ($_POST); I am confused about PHP Post/Redirect/Get

相关:返回按钮重新提交表单数据($_POST)我对 PHP Post/Redirect/Get 感到困惑

回答by Mueen Mehmood Waseer

Add this code in the page that is showing as offline when the user clicks the back button:

在用户单击后退按钮时显示为脱机的页面中添加此代码:

<?php
 session_start();
 header_remove("Expires");
 header_remove("Cache-Control");
 header_remove("Pragma");
 header_remove("Last-Modified");
?>

回答by Jan Wiemers

One way is to submit the Formdata via Ajax to a remote Script and if the Query returns success you can jump the a "Thank You" Page. So the User can hit the Back Button and the "Reload" Request doesn't pop up.

一种方法是通过 Ajax 将 Formdata 提交到远程脚本,如果查询返回成功,您可以跳转到“谢谢”页面。所以用户可以点击后退按钮并且“重新加载”请求不会弹出。

Hope the Idea helps you

希望这个idea能帮到你

回答by Keith DC

Can you do it via an Ajax call instead? No action on the form, and the submit will call a the Ajax function. The Ajax call will execute the query, and provide a response (you can just echo a result), and you can then provide dynamic feedback based on the result. You'd never leave the page.

你可以通过 Ajax 调用来实现吗?在表单上没有任何动作,并且提交将调用一个 Ajax 函数。Ajax 调用将执行查询,并提供响应(您可以只回显结果),然后您可以根据结果提供动态反馈。你永远不会离开页面。

<form id="thisForm">
...form input fields...
<input type="button" onclick="return submitForm('thisForm')"/>
</form>

function submitForm(formId) {
    $.ajax( {
        type: "post",
        url: 'page2.php',
        data: $('#' + formId + ' input').serialize(),
        ... any other Ajax parameters...,
        success: function(data) {
        }
    });
    return false;
}

回答by Jordan

Create a Session like shown here

创建一个会话像显示在这里

You should use session and validate the user from every page and you will amaze how SESSION works! AMAZING!

您应该使用 session 并验证每个页面的用户,您会惊讶于 SESSION 的工作原理!惊人的!