所以我遇到了问题,如果我点击足够快的subnmit按钮,我的表单会被提交几次。我怎么能阻止这个?令牌是自动添加的,但它根本没有帮助。 表格示例:
<div class="row padding-10">
{!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
<div class="form-group">
{!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="col-md-offset-5 col-md-3">
{!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
我的NewsController商店方法:
public function store()
{
$validator = Validator::make($data = Input::all(), array(
'title' => 'required|min:8',
'body' => 'required|min:8',
));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
News::create($data);
return Redirect::to('/news');
}
答案 0 :(得分:4)
一种方法是使用按钮的单击处理程序,首先禁用该按钮,然后提交表单。
<script>
function submitForm(btn) {
// disable the button
btn.disabled = true;
// submit the form
btn.form.submit();
}
</script>
<input id="submitButton" type="button" value="Submit" onclick="submitForm(this);" />
答案 1 :(得分:0)
使用PHP sessions
将会话变量(例如$_SESSION['posttimer']
)设置为发布时的当前时间戳。在PHP中实际处理表单之前,请检查$_SESSION['posttimer']
变量是否存在并检查某个时间戳差异(IE:2秒)。这样,您就可以轻松过滤掉多个提交。
// form.html
<form action="foo.php" method="post">
<input type="text" name="bar" />
<input type="submit" value="Save">
</form>
// foo.php
if (isset($_POST) && !empty($_POST))
{
if (isset($_SESSION['posttimer']))
{
if ( (time() - $_SESSION['posttimer']) <= 2)
{
// less then 2 seconds since last post
}
else
{
// more than 2 seconds since last post
}
}
$_SESSION['posttimer'] = time();
}
原始帖子
How to prevent multiple inserts when submitting a form in PHP?
答案 2 :(得分:0)
如果您使用的是类型为“提交”的按钮,并且还希望提交按钮的值(如果禁用了该按钮,则不会发生),则可以设置表单数据属性,然后进行测试。
// Add class disableonsubmit to your form
$(document).ready(function () {
$('form.disableonsubmit').submit(function(e) {
if ($(this).data('submitted') === true) {
// Form is already submitted
console.log('Form is already submitted, waiting response.');
// Stop form from submitting again
e.preventDefault();
} else {
// Set the data-submitted attribute to true for record
$(this).data('submitted', true);
}
});
});