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">
}
}
上面的代码工作正常,如果用户刷新或使用后退按钮,则不会要求他重新发布数据浏览器。
问题是我想在插入评论时显示一条消息“感谢您的评论”。同时,如果他们提供空评论,我想显示表单和一条消息“请输入评论!”。
我该如何去实现这两个要求?
干杯:)
I would like to implement the Post/Redirect/Get pattern in a page that will post to itself.
The form is part of an MVC application I am building at the moment, and the form fields are generated in php.
The form resides here: http://site.com/mycontroller/myaction/
Here's the relevant code for "myaction" (note that a session has already been started, so I can read and write from $_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">
}
}
The above code works fine, if the user refreshes or uses the back button, he is not asked to repost the data by the browser.
The problem is that I would like to display a message that says "Thanks for commenting" when the comment has been inserted. At the same time, if they provided an empty comment, I would like to display the form and a message that says "Please enter a comment!".
How can I go about implementing these 2 requirements?
Cheers :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
进行以下操作:
我会在 myaction 脚本中
i would make the following:
in myaction script:
有 3 种可能的解决方案
对于错误消息,您可以就地显示它,无需重定向。它的一个缺点是,如果用户最终未能填写表单,则要求用户重新加载页面,但它通常被认为可以忽略不计。
There are 3 possible solutions
For the error message you could show it in place, without redirect. It has an disadvantage of asking a user to reload a page if they fail to fill out the form finally, however it is often considered negligible.