按回按钮后阻止表单重新提交

use*_*382 20 php forms get refresh back

我在这里和其他地方搜索了很多帖子,但似乎无法找到我的问题的解决方案.我有一个显示数据库条目的页面:database.php.可以使用表单过滤这些条目.当我过滤它们并只显示我感兴趣的那些时,我可以点击一个条目(作为链接),它将我带到那个条目页面(通过php GET).当我在该条目页面上(即"view.php?id = 1")并点击后退按钮(返回到database.php)时,过滤器表单需要确认表单重新提交.有什么方法可以防止这种情况吗?

这里有一些(简化的)代码示例:

database.php中:

<form>
    <select>
        <option>1</option>
        <option>2
        <option>
    </select>
    <input type="submit" name="apply_filter" />
</form>
<?php
if ( isset( $_POST[ "apply_filter" ] ) ) { // display filtered entries
    $filter = $_POST[ "filter" ];
    $q = "Select * from table where col = '" . $filter . "'";
    $r = mysql_query( $q );
} else { // display all entries
    $q = "Select * from table";
    $r = mysql_query( $q );
}
while ( $rec = mysql_fetch_assoc( $r ) ) {
    echo "<a href='view.php?id=" . $rec[ "id" ] . "'>" . $rec[ "name" ] . "</a><br />"; // this is where the link to the view.php page is...
}
?>
Run Code Online (Sandbox Code Playgroud)

现在如上所述,如果我点击链接,它会带我去"view.php?id = whatever".在该页面上,我只是从URL获取ID以显示该单个条目:

view.php:

<?php
$id = $_GET[ "id" ];
$q = "Select * from table where id = '" . $id . "'";
$r = mysql_query( $q );
while (  ) {
    // display entry
}

?>
Run Code Online (Sandbox Code Playgroud)

如果我现在点击后退按钮,database.php上的表单(用于过滤数据库结果的表单)需要确认重新提交.这不仅非常烦人,对我来说也没用.

我怎样才能解决这个问题?我希望代码示例和我的问题的解释是充分的.如果不让我知道,我会尽力指定.

小智 23

我知道这个问题已经过时了,但是我自己也有这个问题,我发现有两条线可以解决:

header("Cache-Control: no cache");
session_cache_limiter("private_no_expire");
Run Code Online (Sandbox Code Playgroud)


Phi*_*ger 8

我知道有两种方法可以做到这一点.简单的方法和艰难的方式.

无论如何,当您处理基于状态的页面(使用$_SESSION)时,您应该做的是保持页面"实时"并且在您的控制之下,这样可以防止所有页面的缓存如下:

<?php
//Set no caching
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
Run Code Online (Sandbox Code Playgroud)

困难的方法是生成一个id并将其作为隐藏输入或&_SESSIONcookie 存储在页面的某个位置.然后在服务器上存储相同的ID作为$_SESSION.如果它们不匹配,则一系列预编程if else类型语句不会导致重新提交页面(这是单击后面时尝试执行的操作).

如果表单已成功提交,简单的方法是简单地将用户重定向回表单提交页面,如下所示:

header('Location: http://www.mydomain.com/redirect.php');
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!


归档时间:

查看次数:

41574 次

最近记录:

6 年,1 月 前