防止表单重复提交

时间:2022-09-12 16:46:54

js禁用按钮:

function doSubmit(){
$(
"#submitBtn").attr("disabled","disabled");
$(
"#submitBtn").text('保存中...');
var formData = $('#submitForm').serialize();
$.ajax({
type:
'POST',
async:
true,
timeout:
10000,
url:
'/user/updateinfo',
data:formData,
dataType:
'json',
success:
function(data){
if(data.status==true){
alert(
'保存成功');
}
else{
alert(data.message);
}
$(
"#submitBtn").removeAttr("disabled");
$("#submitBtn").text('保存');
return false;
},
error:
function(e,textStatus, errorThrown){
$(
"#submitBtn").removeAttr("disabled");
$(
"#submitBtn").text('保存');
alert(
'发生错误,请重试');
return false;
}
});
}

 

php session控制:

public function form(){
$_SESSION['token'] = mt_rand(1, 9999);
}

public function submit(){
if(empty($_POST['token']) || empty($_SESSION['token']) || $_POST['token']!=$_SESSION['token']){
exit;
}
else{
unset($_SESSION['token']);
}
}

 

form:

<form method="post" id="submitForm" onsubmit="return doSubmit()">
<input type="hidden" name="token" value="<?=$_SESSION['token']?>" />
<input type="text" name="username" value="" />
<button type="submit" id="submitBtn">保存</button>
</form>