网站中防止表单重复提交是一个比较普遍的需求,解决办法很多种
有利用session和cookie即生成个一次性token放在表单隐藏域防重复提交
有利用js设置变量锁定
这里以设置表单失效来实现
<!DOCTYPE html>
<html>
<head>
<title>注册</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta charset="utf-8">
<script src="../jquery-1.7.2.min.js"></script>
<style>
.submit-btn{ color: #fff;background-color: #7d61dd;}
.disabled{
background-color: #bbbbbb;
cursor: not-allowed;
color: #848484;
text-shadow: 0 1px 0 #f5f5f5;
}
</style>
</head>
<body class="">
<form action="ajax.php" name="form1" id="form1" class="form-horizontal" autocomplete="off">
<input type="text" name="username">
<input type="hidden" name="token" value="提交">
<input type="button" class="submit-btn ajax-post" name="" value="提交" target-form="form-horizontal">
</form>
<script>
//ajax post submit请求
$(document).ready(function() {
$(".ajax-post").click(function(){
var that = this;
$(that).addClass('disabled').attr('autocomplete','off').prop('disabled',true);
$.post("ajax.php",
$("#form1").serialize(),
function(data){
if(data.status==1){
}else{
alert(data.info)
}
$(that).removeClass('disabled').prop('disabled',false);//注意post里this标识jquery 所以得用that存储 或者$(".ajax-post")
},
'json');
return false;
})
})
</script>
</body>
</html>
<?php
sleep(2);
$conn=mysql_connect("localhost","root","123456")or die ('连接数据库服务器失败:'.mysql_error());;
mysql_select_db("test",$conn);
mysql_query("set names 'utf8'");
$username=$_REQUEST['username'];
$sql="insert into user(number)values($username)";
$query=mysql_query($sql);
$json=array('status'=>1,'info'=>'信息');
mysql_close($conn);
echo json_encode($json);
?>