2014-12-29 227 views
1

所以我遇到了問題,如果我點擊速度足夠subnmit按鈕,我的表單submited幾次。我怎樣才能防止這一點?令牌是自動添加的,但它根本無助於我的猜測。 形式例如:防止通過點擊快速laravel多次提交表格

<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

您可以禁用表格提交後提交按鈕被點擊的javascript'的preventDefault()'。 – jsxqf

回答

3

一種方法是使用一個點擊處理程序,它首先禁止按鈕按鈕,然後提交表單。

<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);" /> 
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?