我想在一个将发布到自身的页面中实现Post / Redirect / Get模式。
表单是我正在构建的MVC应用程序的一部分,表单字段是在php中生成的。
表单位于此处:http://site.com/mycontroller/myaction/
以下是“myaction”的相关代码(请注意,会话已经启动,所以我可以从$ _SESSION读取和写入):
public function myaction(){
$login = $_POST['comment'];
if(isset($comment)){
//I am not doing any real checking here as I am just testing the redirect. Just checking to see if a value was supplied to the comment text input.
$_SESSION['test'] = 'SUCCESS';
//Insert the comment here (into some database).
header("Location: http://site.com/mycontroller/myaction/", 302);
exit();
echo "<BR>Thanks for commenting! <BR>";
}else{
//Show the form here.
//The form posts to itself, so the action looks like: <form action="" method="POST">
}
}
上述代码工作正常,如果用户刷新或使用后退按钮,则不会要求他通过浏览器重新发布数据。
问题是我想在插入评论时显示“感谢评论”的消息。同时,如果他们提供了空白评论,我想显示表格和“请输入评论!”的消息。
我如何实施这两项要求?
干杯:)
答案 0 :(得分:1)
有3种可能的解决方案
对于错误消息,您可以将其显示在原位,而无需重定向。它的缺点是,如果用户最终未能填写表单,则要求用户重新加载页面,但通常认为这可以忽略不计。
答案 1 :(得分:0)
我会做以下事情:
header("Location: http://site.com/mycontroller/myaction/?aftercomment=true", 302);
在myaction脚本中:
if ($_GET['aftercomment']) echo('Thanks for comment!');
答案 2 :(得分:0)
public function myaction(){
if(isset($_GET['ok'])) {
echo "<BR>Thanks for commenting! <BR>";
}
$comment = $_POST['comment'];
if(isset($comment)){
//I am not doing any real checking here as I am just testing the redirect. Just checking to see if a value was supplied to the comment text input.
$_SESSION['test'] = 'SUCCESS';
//Insert the comment here (into some database).
header("Location: http://site.com/mycontroller/myaction/?ok=1", 302);
exit();
echo "<BR>Thanks for commenting! <BR>";
}else{
echo "Please enter a comment!";
//Show the form here.
//The form posts to itself, so the action looks like: <form action="" method="POST">
}
}