所以我有这两页: pageOne.php
和 pageTwo.php
。表格在 pageOne.php
中:
<form method="post" action="pageTwo.php"> .... </form>
并在
pageTwo.php
中完成所有数据收集-验证-插入和发送邮件(我在两个单独的页面中进行所有操作的原因是为了避免在页面刷新时重新提交数据......这是我最简单的方法处理问题)。到目前为止,一切都运行良好。现在,我想在提交表单后使用警告框显示成功/失败消息,并尝试了一些没有运气的事情。例如。当我在
pageTwo.php
上尝试 THIS 解决方案时,没有出现弹出框,我认为这是因为我在该页面顶部有这个 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>";
?>
当在
pageOne.php
中尝试这个 second solution 时,我每次刷新页面时都会弹出警告框并收到失败消息,即使数据已插入数据库并发送邮件。 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 的 sugession 做了一些改变,这就是我到目前为止所拥有的......
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/