当我的页面发布帖子时,我会将所有$_POST
数据存储在单独的$_SESSION
变量中。我知道同一页面的后退按钮旨在显示Document Expired
消息。我的希望是欺骗浏览器,让浏览器认为真的从来没有任何$_POST
数据,因此在返回数据时不要显示Document Expired
消息。我正在强制完全刷新页面,所以我不必担心接收旧数据,因为我已将其存储在会话中。
我试图unset($_POST)
希望这将留在页面上。 但是$_POST
数据必须缓存/存储,并使用刷新或后退按钮返回。我正在尝试做的事情可能吗?有什么想法吗?
*更新*我的解决方案/答案发布在下面。它发布到一个单独的表单,该表单重定向回原始表单进行处理。不知道为什么投反对票。几个月来它一直运行良好,我不再收到文档过期消息。它还可以防止重复发布。
您可以使用帖子 - 重定向 - 获取设计模式来实现这一点。
http://en.wikipedia.org/wiki/Post/Redirect/Get
实现此模式的更标准方法是在一个页面上显示、验证和保存表单。
以下解决方案具有以下优点:
1.所有与表单相关的代码都在一个地方。2. 服务器端验证简单
我有两页,表格.php和之后.php。
形式.php :
if(isPosted()){
if(dataIsValid($postedData)){
// dataIsValid should set $message to show to the user
saveData($postedData);
redirect('after.php');
die();
}
} else {
$postedData = $defaultValues;
}
showForm($postedData, $message);
您可以将以下内容添加到脚本的开头以解决此问题。
header("Cache-Control: max-age=300, must-revalidate");
的最简单的解决方案? 不要直接做帖子,赶上事件并通过 AJAX 提交表单。 然后在成功时,重定向。
使用 jQuery 的示例:
$('#some_form').submit(function() {
$.post($(this).attr('action'), $(this).serialize(), function() {
window.location = "/some/success/url.php";
});
return false; // Prevent the form submission & any other events triggered on submit
});
由于 POST 从未添加到浏览器历史记录中,因此您不会遇到此问题。
但是,请注意,POST url 现在与您加载的 url 不同;您可以通过检查 POST 或 GET 是在服务器端完成的,但无论哪种方式,您都必须做一些额外的工作来"记住"POST 的结果。
更新 *这是我的解决方案。
我知道,使用后重定向-get,POST通常会返回到同一页面进行处理,然后再通过GET从表单重定向到另一个目的地。但是,我需要能够返回到原始页面进行重新编辑(就像在用户可以保存正在进行的工作的文档模型中一样)。因此,将 POST 转到第二页并重定向回原始页面是我摆脱"已过期"消息的想法,因为编辑表单不会有与之关联的 post 数据。我已经扩展了它(未显示)以包括 $_FILE 和其他情况(例如,也将其与a href
一起使用)。不知道为什么投反对票。几个月来,这已经运行良好并完成了任务。我不再收到"文档已过期"消息。此外,所有 _POST 美元的处理都在原始文件中完成。
测试表格.php
<?php
session_start();
if (isset($_GET) && count($_GET)>0){
// process get
var_dump($_GET);
}
if (isset($_SESSION['post-copy'])){
// return post vars to $_POST variable so can process as normal
$_POST = $_SESSION['post-copy'];
// unset the session var - with refresh can't double process
unset($_SESSION['post-copy']);
// process post vars
var_dump($_POST);
}
?>
<form method='post' action='__b.php?redirect=<?php echo $_SERVER['PHP_SELF'] ?>&help=me' enctype='multipart/form-data'>
<textarea name='descr' id='descr'>ABCD</textarea>
<input type='submit' value='Go'>
</form>
重定向.php
<?php
if (!isset($_SESSION)){
session_start();
}
if (isset($_POST)){
$_SESSION['post-copy'] = $_POST;
}
// retrieve the url to return to
if (isset($_GET['redirect'])){
$url = $_GET['redirect'];
}
// if multiple query string parameters passed in get, isolate the redirect so can build querystring with the rest
if (isset($_GET) && count($_GET) > 1){
$get = $_GET;
foreach ($get as $key => $val){
if ($key == 'redirect'){
// remove from rest of passed get query string
unset($get[$key]);
}
}
if (count($get) > 0){
$url .= (strpos($url,"?")===false ? "?" : "&") . http_build_query($get);
}
}
if ($url!==""){
header("Location: " . $url);
}
?>