如何在页面刷新时停止表单重新提交
9 个回答
- 投票数
-
- 2013-04-20
代替……
} else { echo "<p>Your file has been uploaded.</p>"; }
…成功重定向到另一个地址:
} else { $new_url = add_query_arg( 'success', 1, get_permalink() ); wp_redirect( $new_url, 303 ); exit; }
主要存在此方法是为了允许POST激活的脚本输出将用户代理重定向到所选资源.新URI不能替代原始请求的资源. 303响应一定不能被缓存,但是对第二个(重定向的)请求的响应可能是可缓存的.
在表单处理程序中,首先检查是否设置了
$_GET['success']
,并且其值为1
,然后打印成功消息.访客可以一次又一次地重新加载此页面-不会发送任何内容.Instead of …
} else { echo "<p>Your file has been uploaded.</p>"; }
… redirect to another address on success:
} else { $new_url = add_query_arg( 'success', 1, get_permalink() ); wp_redirect( $new_url, 303 ); exit; }
Status code 303 triggers a GET request:
This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource. The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.
In your form handler check first if
$_GET['success']
is set and its value is1
, then print a success message. The visitor can reload this page again and again – and nothing will be sent.-
不幸的是,这没有用,我也不知道为什么因为那个php确实粘住了(只是为了确认我应该做的就是替换回声?Unfortunately that didn't work, and I have no idea why because that php does stick up (just to confirm all I was supposed to do was replace the echo?
- 0
- 2013-04-20
- ameeromar
-
您必须先发送标头,然后才能将任何输出发送到浏览器.You have to send the header before any output has been sent to the browser.
- 1
- 2013-04-20
- fuxia
-
所以把php代码放在标题中?so put the php code bit in the header?
- 0
- 2013-04-26
- ameeromar
-
@ameeromar是的.开始创建输出之前,应完成所有数据处理.@ameeromar Yes. All data processing should be done before you start creating output.
- 2
- 2013-04-26
- fuxia
-
- 2013-09-11
我遇到了同样的问题,并且由于我将所有URL重定向到单个.php文件而使情况"复杂化".事实证明,解决该问题所需要做的就是在将任何html写入页面之前插入以下代码.
<?php if (isset($_POST['mypostvar']) && isset($_SERVER['REQUEST_URI'])) { [process the post data in 'mypostvar'] header ('Location: ' . $_SERVER['REQUEST_URI']); exit(); } ?>
根据需要处理后数据后,它将重定向到同一页面. 重定向后,原始邮寄数据将消失,并且不会触发重新提交. 仅当在将任何内容写入页面之前将其插入时,函数" header()"才起作用. exit()是必需的.
在放置header()之前必须处理帖子数据.
I had the same problem and it was "complicated" by the fact that I redirect all URLs to a single .php file. It turned out all I had to do to solve it was to insert the following piece of code before any html is written to the page.
<?php if (isset($_POST['mypostvar']) && isset($_SERVER['REQUEST_URI'])) { [process the post data in 'mypostvar'] header ('Location: ' . $_SERVER['REQUEST_URI']); exit(); } ?>
This will redirect to the same page after the postdata is processed as you want it. After the redirect the original postdata is vanished and will not trigger the resubmit. The function 'header()' will only work if you insert it before anything is written to the page. exit() is necessary.
You have to process the post data before you place the header().
-
- 2018-05-11
基本上,一般的想法是在提交表单后将用户重定向到其他页面,这将在刷新页面时停止重新提交表单,但是如果您需要在提交表单后将用户保留在同一页面中,则可以以多种方式做到这一点.
未设置表单数据
一种阻止页面刷新时重新提交页面的方法是在提交表单后取消设置表单数据,以使存储表单数据的变量变为空,并包装表单处理代码块以检查表单是否为空.
if(!empty($ _ POST)&& $ _SERVER ['REQUEST_METHOD']=='POST'){ $ data=//在这里处理代码 取消设置$ data; }
这将使$ data在处理后为空,并且第一个子句将在页面刷新时停止重新提交表单.
JavaScript
此方法非常简单,一旦提交表单,就会阻止弹出窗口要求刷新时重新提交表单.只需将这行javascript代码放在文件的页脚处,然后看一下魔术.
&lt; script&gt; 如果(window.history.replaceState){ window.history.replaceState(null,null,window.location.href); } &lt;/script&gt;
Basically, the general idea is to redirect the user to some other pages after the form submission which would stop the form resubmission on page refresh but if you need to hold the user in the same page after the form is submitted, you can do it in multiple ways.
Unset Form Data
One way to stop page resubmission on page refresh is to unset the form data after it is submitted so that the variable storing form data becomes empty and wrap up your form processing block of codes to check if the form is empty.
if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){ $data = // processing codes here unset $data; }
This will make $data empty after processing and the first clause would stop form resubmission on page refresh.
Javascript
This method is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.
<script> if ( window.history.replaceState ) { window.history.replaceState( null, null, window.location.href ); } </script>
-
- 2013-09-12
我使用template_redirect操作(在插件中或在您的themes.php文件中)解决了此问题.
add_action('template_redirect','myfunction') ; function myfunction() { global $post; $post_id = $post->ID; if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) { require_once(ABSPATH . 'wp-admin/includes/admin.php'); $id = media_handle_upload('async-upload', $post_id); //post id of Client Files page unset($_FILES); if ( is_wp_error($id) ) { $errors['upload_error'] = $id; $id = false; } } $error = ($errors) ? 1 : 0; wp_redirect( "/?p={$post_id}?errors={$error}",301); }
然后在页面上可以检查错误
if ($_GET['errors']) { echo "<p>There was an error uploading your file.</p>"; } else { echo "<p>Your file has been uploaded.</p>"; }
(我尚未测试此代码.它应该为您提供一个很好的起点).
I solved this my using the template_redirect action (either in a a plugin or on your themes functions.php file).
add_action('template_redirect','myfunction') ; function myfunction() { global $post; $post_id = $post->ID; if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) { require_once(ABSPATH . 'wp-admin/includes/admin.php'); $id = media_handle_upload('async-upload', $post_id); //post id of Client Files page unset($_FILES); if ( is_wp_error($id) ) { $errors['upload_error'] = $id; $id = false; } } $error = ($errors) ? 1 : 0; wp_redirect( "/?p={$post_id}?errors={$error}",301); }
Then on your page you can check for errors
if ($_GET['errors']) { echo "<p>There was an error uploading your file.</p>"; } else { echo "<p>Your file has been uploaded.</p>"; }
(I've not tested this code.. it should give you a good starting point).
-
在第一行使用`global $post`时,此功能起作用的机会将会增加...With `global $post` in first line, chances this function works will increase...
- 1
- 2013-09-12
- gmazzap
-
- 2013-09-12
您还可以测试
$_SERVER['REQUEST_METHOD'] === 'POST'
,以确保在处理表单之前已通过POST刷新了页面.if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { // Do Stuff }
You can also test for
$_SERVER['REQUEST_METHOD'] === 'POST'
to make sure that the page has been refreshed via POST before processing the form.if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { // Do Stuff }
-
- 2016-01-09
一种更简单的方法是从表单中删除该操作并进行隐藏操作,例如:
<html> <form action="" method="post><input type="text" name="name" /> <input type="submit" value="Submit" /> <input type="hidden" name="action" value="Submit" /> </form> </html>
让您的控制器检查有效性和提交内容,以便检查表单是否已提交:
<?php if (isset($_POST['action']) && $_POST['action'] == 'Submit'){ //you should add code to validate user input here //if all ok submit the form header('Location: .'); //redirects to the controller without resubmitting } ?>
此方法对于在管理页面上添加或删除记录的脚本非常有用,因为它将重新加载页面而无需重新提交,并且删除或添加的记录将被删除或添加到页面:)
an easier way is to remove the action from your form and have a hidden action so for example:
<html> <form action="" method="post><input type="text" name="name" /> <input type="submit" value="Submit" /> <input type="hidden" name="action" value="Submit" /> </form> </html>
have your controller checking for validity and for submissions so to check if the form was submitted:
<?php if (isset($_POST['action']) && $_POST['action'] == 'Submit'){ //you should add code to validate user input here //if all ok submit the form header('Location: .'); //redirects to the controller without resubmitting } ?>
this method is very useful for scripts where you are adding or removing records on an admin page as it would reload the page without resubmitting and the record removed or added would be either removed or added to the page :)
-
- 2017-06-23
我发现的最好方法是使用javascript和CSS.常见的php重定向方法标头(位置: http://www.yourdomain.com/url );可以正常工作,但是会在不同的框架和cms(如wordpress,drupal等)中引发"警告:无法修改标题信息-标题已发送"警告.因此,我的建议是遵循以下代码
echo '<style>body{display:none;}</style>'; echo '<script>window.location.href = "http://www.siteurl.com/mysuccesspage";</script>'; exit;
样式标签很重要,否则用户可能会感觉页面已加载两次.如果我们在样式标签上不显示任何内容,然后刷新页面,则用户体验将与php header('Location:....);
我希望这会有所帮助:)
The best method I found is using javascript and css. Common php redirection method header('Location: http://www.yourdomain.com/url); will work but It cause warning " Warning: Cannot modify header information - headers already sent" in different frameworks and cms like wordpress, drupal etc. So my suggestion is to follow the below code
echo '<style>body{display:none;}</style>'; echo '<script>window.location.href = "http://www.siteurl.com/mysuccesspage";</script>'; exit;
The style tag is important otherwise the user may feel like page loaded twice. If we use style tag with body display none and then refresh the page , then the user experience will be like same as php header('Location: ....);
I hope this will help :)
-
- 2020-04-30
解决方案1: 如果要以帖子类型插入帖子,则只需使用
rand()
php函数生成随机代码,然后在插入帖子时保存代码.还要在$_POST['uniqueid']
变量中设置相同的代码.然后检查插入是否当前的唯一ID在帖子中,您可以使用
wp_query()
进行相同操作.解决方案2: 使用javascript重定向到另一个页面.但是,好心的不是那个用户可以返回页面,然后再次将其保存在刷新时.对于这个问题,第一个解决方案是最好的.
解决方案3: 使用ajax插入帖子将不会出现这样的问题.但是,如果您想点击网页.这不是一个好主意,可能适用于Google Adsense.
我只是想以自己的经验为您提供帮助.如果有人需要代码来解决问题,只需问一下,我会分享.
Solution 1 : If you are inserting post in post type then just generate the random code using
rand()
php function and save the code while inserting post. Also set the same code in$_POST['uniqueid']
variable.Then check on insert if the the current uniqueid is there in posts or not, you can do the same using
wp_query()
.Solution 2 : Redirect to another page using javascript. But kindly not that user can go back to page and on again it will save post on refresh. For this issue the first solution is best.
Solution 3 : Use ajax to insert post there will be no issues like this. But if you want page hits. It's not a good idea, may be for Google Adsense.
I just tried to help by my experience. If anyone need code to fix the problem, simply ask, I will share.
-
- 2014-12-07
在php中执行此操作的简单方法. 此处的示例:
别忘了html标签(这种形式在这里不允许使用,所以我用[this])
$firstname = $post[firstname] $lastname = $post[lastname] [form action="here.php" method="post"] first name[input type='firstname' name='firstname'] last name[input type='text' name='lastname'] [input type=submit value=submit] [/form] if($firstname==""||$lastname=="") { echo"the firstname and lastname are empty"; } else { mysql_query("YOUR DATABASE INSERT HERE"); header("Location:here.php"); }
这是保持数据输入数据库的方式,以防止在页面刷新时两次发布相同的数据
the simple and easy way to do this in php. example here:
dont forget the html tags(this form wont allow it here so i use [this])
$firstname = $post[firstname] $lastname = $post[lastname] [form action="here.php" method="post"] first name[input type='firstname' name='firstname'] last name[input type='text' name='lastname'] [input type=submit value=submit] [/form] if($firstname==""||$lastname=="") { echo"the firstname and lastname are empty"; } else { mysql_query("YOUR DATABASE INSERT HERE"); header("Location:here.php"); }
this is how to keep the data enter in the database from posting the same data twice on page refresh
您好,我有一个将附件添加到帖子中的表单,但是当表单发布时,它显然不显示带有新附件并显示"您的文件已上传"的帖子.当用户刷新页面(尝试显示其新附件)时,表单再次发布!
是否可以(1)刷新时停止表单发布,(2)自动刷新页面以显示带有新附件的帖子? (2更好)
谢谢! :)