简体   繁体   English

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

[英]Prevent resubmit form after click “back” button

I have 2 pages : 我有2页:

page1.php : page1.php:
- has a form with text box and a "submit" button. - 有一个带有文本框和“提交”按钮的表单。 Eg : <form name="frm_register" action="page1.php" method="post"> 例如: <form name="frm_register" action="page1.php" method="post">

- php and mysql code to store the value of textbox to database. - 用于将textbox的值存储到数据库的php和mysql代码。 Javascript will redirect the page to php2.php after the value is submitted to database. 将值提交到数据库后,Javascript会将页面重定向到php2.php Eg : 例如:

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

page2.php 使page2.php
- mysql retrieve the data from database and display on this page. - 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? 是否需要清除page1.php的缓存? How to do it with php or javascript or ajax? 如何用php或javascript或ajax做到这一点?


Update 1 : Thanks for the answer of replacing javascript window.location="page2.php" to php header('Location: home2.php'); 更新1:感谢您将javascript window.location="page2.php"替换为php header('Location: home2.php'); . It fix 80% of problem. 它解决了80%的问题。 The rest of 20% problem show below : 剩下的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. 1)用户成功提交数据,跳转到page2.php查看记录。
2) User click "back" button, jump back to page1.php. 2)用户点击“返回”按钮,跳回page1.php。
3) User submit data fail, stay on page1.php. 3)用户提交数据失败,留在page1.php。 (because too fast or same name) (因为太快或同名)
4) User submit data successful, jump to page2.php view records. 4)用户提交数据成功,跳转到page2.php查看记录。
5) User click "back" button, but browser shows warning message "form will be resubmited". 5)用户点击“返回”按钮,但浏览器显示警告信息“表格将被重新提交”。

The problem is because of Step 3. Step 3 didn't run header('Location: page2.php'); 问题是由于步骤3.步骤3没有运行header('Location: page2.php'); , didn't jump to page2.php. ,没有跳到page2.php。 So it cause Step 5 show the warning message. 因此它会导致步骤5显示警告消息。 How to fix this problem? 如何解决这个问题?


Update 2 : I have figured out the solution to fix the 20% problem, it works perfectly. 更新2:我已经找到了解决20%问题的解决方案,它运行得很好。 I use session['error123'] to decide whether or not want to display the error message "same name". 我使用session['error123']来决定是否要显示错误消息“同名”。 I kill session['error123'] if success submit data to database or if success jump to page2.php. 如果成功将数据提交到数据库或成功跳转到page2.php,我session['error123'] I also use header('Location: page1.php'); 我也使用header('Location: page1.php'); to redirect to own page (same page) to make the page forget about form submission previously. 重定向到自己的页面(同一页面),使页面忘记以前的表单提交。 Example of codes : 代码示例:

 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(). 注意:您需要通过<?php ob_start();?>缓冲输出,因为$ _SESSION不能放在header()之前。 Buffer will stop all output including session, let header() send the output first. Buffer将停止所有输出,包括session,让header()先发送输出。

Rather than 而不是

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 单击页面上的提交.php action page1.php page1.php将数据提交给数据库调用

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

This should prevent your clicking back problem 这应该可以防止您点击回来的问题

You can prevent the re-submission by implementing the Post-Redirect-Get (PRG Pattern) . 您可以通过实施Post-Redirect-Get(PRG模式)来阻止重新提交。

Could be just a one-line if you've got the http_redirect function: 如果你有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.com with site's your hostname. example.com替换为site的主机名。

Related: Back button re-submit form data ($_POST) ; 相关: 后退按钮重新提交表单数据($ _POST) ; I am confused about PHP Post/Redirect/Get 我对PHP Post / Redirect / Get感到困惑

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");
?>

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. 一种方法是通过Ajax将Formdata提交到远程脚本,如果Query返回成功,您可以跳转到“谢谢”页面。 So the User can hit the Back Button and the "Reload" Request doesn't pop up. 因此,用户可以点击后退按钮,并且不会弹出“重新加载”请求。

Hope the Idea helps you 希望这个想法可以帮助你

Can you do it via an Ajax call instead? 你可以通过Ajax调用吗? No action on the form, and the submit will call a the Ajax function. 表单上没有任何操作,提交将调用Ajax函数。 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. Ajax调用将执行查询,并提供响应(您可以只回显结果),然后您可以根据结果提供动态反馈。 You'd never leave the page. 你永远不会离开这个页面。

<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;
}

Create a Session like shown here 创建一个会话像显示在这里

You should use session and validate the user from every page and you will amaze how SESSION works! 你应该使用会话并从每个页面验证用户,你会惊讶于SESSION如何工作! AMAZING! 惊人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM