所以我有这两个页面:pageOne.php
和pageTwo.php
。表单在pageOne.php
中:
<form method="post" action="pageTwo.php"> .... </form>
并在 pageTwo.php
中完成所有数据收集-验证-插入和发送邮件(我在两个单独的页面中执行所有操作的原因是为了避免在页面上重新提交数据刷新...这是我处理问题的最简单方法)。到目前为止一切正常。
现在,我想在提交表单后使用警告框显示成功/失败消息,并尝试了一些没有运气的事情。例如。当我尝试 THIS pageTwo.php
上的解决方案,没有弹出框出现,我想那是因为我在那个页面的顶部有这个 header
<?php header("Location: http://TestPages.com/pageOne.php"); ?>
<?php
if( $_POST ) {
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
echo "<script type='text/javascript'>alert('It worked!')</script>";
}else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
当尝试这个时 second solution在 pageOne.php
中,每次刷新页面时我都会弹出警告框并收到失败消息,即使数据已插入数据库并已发送邮件。 pageOne.php
:
<html>
<body>
<?php
if( $GLOBALS["posted"]) //if($posted)
echo "<script type='text/javascript'>alert('It worked!')</script>";
else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
<form method="post" action="pageTwo.php"> .... </form>
</body>
在 pageTwo.php
中:
<?php header("Location: http://TestPages.com/pageOne.php"); ?>
<?php
$posted = false;
if( $_POST ) {
$posted = true;
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
} ?>
为什么这个简单的东西不起作用:(?有什么简单的方法可以解决这个问题吗?谢谢!!
更新
所以我根据 drrcknlsn 的建议做了一些更改,这是我目前所做的....pageOne.php
:
<?php
session_start();
if (isset($_SESSION['posted']) && $_SESSION['posted']) {
unset($_SESSION['posted']);
// the form was posted - do something here
echo "<script type='text/javascript'>alert('It worked!')</script>";
} else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
<html> <body>
<form method="post" action="pageTwo.php"> .... </form>
</body> </html>
和pageTwo.php
:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['posted'] = true;
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
header('Location: http://TestPages.com/pageOne.php');
exit;
} ?>
有了这些更改,页面的重定向和成功消息现在可以正常工作,但每次打开/刷新页面时我都会收到失败消息(我知道那是因为 session key 尚未设置)...如何我可以避免吗?再次感谢!!
最佳答案
首先,有几点:
变量(甚至是全局变量)不会在请求之间共享,就像您在底部示例中尝试做的那样。为了使
$posted
可以在两个页面中访问,您必须以某种方式持久化它。通常这涉及设置 session 变量(例如$_SESSION['posted'] = true;
),但它也可以保存在 cookie、数据库、文件系统、缓存中,等等使用
if ($_SERVER['REQUEST_METHOD'] === 'POST')
而不是if ($_POST)
。 虽然后者在大多数情况下可能是安全的,但最好养成使用前者的习惯,因为存在一种边缘情况,其中$_POST
可以为空且有效POST
请求,这可能是一个很难追踪的错误。
使用上述建议解决您的问题的一种潜在模式:
pageOne.php:
<?php
session_start();
if (isset($_SESSION['posted']) && $_SESSION['posted']) {
unset($_SESSION['posted']);
// the form was posted - do something here
}
?>
...
<form>...</form>
pageTwo.php:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['posted'] = true;
// do form processing stuff here
header('Location: pageOne.php');
exit;
}
// show an error page here (users shouldn't ever see it, unless they're snooping around)
关于php - 提交表单时显示警告框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176986/