(转)PHP防止表单重复提交
防止重复提交表单的方法网上蛮多的,有js的也有用cookie和session的,我用的方法是session来判断的。
下面贴上几种方法:
一:js:<input type="button" value="只提交一次" onclick="this.disabled=true;this.form.submit()" /> 把按钮变成灰色
jquery代码:
- <script type="text/javascript">
- $("input:submit").each(function() {
- var srcclick = $(this).attr("onclick");
- if(typeof(srcclick)=="function"){
- $(this).click(function() {
- if (srcclick()) {
- setdisabled(this);
- return true;
- }
- return false;
- });}
- });
- function setdisabled(obj) {
- setTimeout(function() { obj.disabled = true; }, 100);
- }
- </script>
二:php中cookie方法:
t1.php
- <form id="form1" name="form1" method="post" action="t2.php">
- <p>说明
- <input type="text" name="titile" />
- </p>
- <p>
- <input type="submit" name="Submit" value="提交" />
- </p>
- </form>
PHP代码
- <?php
- setcookie("onlypost", 't'); //设置cookie
- ?>
- t2.php
- PHP代码
- <?php
- if($_COOKIE['onlypost'] == 't'){
- print_r($_COOKIE);
- //处理提交的内容
- setcookie("onlypost", 'f'); //改变 cooike值 删除也可以了
- }
- // 其他代码
- ?>
三:session方法,也就是我用的:
t1.php
- <form id="form1" name="form1" method="post" action="t2.php">
- <p>说明
- <input type="text" name="titile" />
- </p>
- <p>
- <input type="submit" name="Submit" value="提交" />
- </p>
- </form>
PHP代码
- <?php
- $_SESSION['onlypost']="t"//设置session
- ?>
t2.php
- <?php
- if($_SESSION['onlypost']=="t"){
- print_r($_SESSION);
- //处理提交的内容
- $_SESSION['onlypost']=="f"; //改变 session的值 删除也可以了
- }
- // 其他代码
- ?>