如何使用$ .ajax(); 在laravel中的function

我需要通过ajax添加新对象,但我不知道如何在laravel中使用$ .ajax()函数。

我在刀片模板中的forms是:

{{Form::open(array('url'=>'expense/add', 'method' => 'POST', 'class' => 'form-signin', 'id' => 'expenseForm'), array('role'=>'form'))}} {{Form::select('period_id', $data['period'], null, array('class' => 'form-control'))}} {{Form::select('expense_category_id', $data['categories'], null, array('class' => 'form-control'))}} {{Form::text('date_expense', null, array('placeholder' => 'Fecha', 'class' => 'form-control'))}} {{Form::text('amount', null, array('placeholder' => '¿cuanto fue?', 'class' => 'form-control'))}} {{Form::hidden('user_id', Auth::user()->id)}} 
{{Form::button('Add expense', array('class'=>'btn btn-lg btn-primary btn-block', 'id' => 'btnSubmit'))}} {{Form::close()}}

我在控制器中的代码是:

 public function addExpense(){ $expense = new Expense; $data = Input::all(); if ($expense->isValid($data)) { $expense->fill($data); $expense->save(); //Recargar la tabla gastos return Redirect::to('expense/index')->with('success', 'El gasto ha sido agregado correctamente.'); } return Redirect::back()->withInput()->withErrors($expense->errors); } 

我的js是:

 $("#btnSubmit").click(submitExpenses); 

这是我的函数submitExpenses

 var submitExpenses = function(){ console.log("Llega aquí :O"); $("form#expenseForm").submit(function(){ $.ajax({ type: 'post', cache: false, dataType: 'json', data: $('form#expenseForm').serialize(), beforeSend: function() { //$("#validation-errors").hide().empty(); }, success: function(data) { console.log("Success!"); }, error: function(xhr, textStatus, thrownError) { alert('Something went to wrong.Please Try again later...'); } }); }); }; 

感谢帮助! :d

您需要更改ajax请求并添加一个URL以将POST数据提交到:

 $.ajax({ url: '/your/route/to/addExpense/method' type: 'post', cache: false, dataType: 'json', data: $('form#expenseForm').serialize(), beforeSend: function() { //$("#validation-errors").hide().empty(); }, success: function(data) { console.log("Success!"); }, error: function(xhr, textStatus, thrownError) { alert('Something went to wrong.Please Try again later...'); } }); 

但那不是全部

看起来你构建了表单,以便它也可以容纳非javascript提交。 这很好,但是,当您单击按钮时,不仅会发送ajax请求,而且还会提交表单。 更改submitExpenses函数以接受事件对象作为参数,以便您可以在单击按钮时取消默认操作:

 var submitExpenses = function(e){ e.preventDefault(); ... 

还有一件事

当您通过ajax提交请求时,您将收到回复。 在您的控制器中,您实际上是在重定向用户,在发出ajax请求时您不想这样做。 在您的请求中,您指定要将某些返回数据以json格式发送给您。 您需要在控制器中更改这些行:

 return Redirect::to('expense/index')->with('success', 'El gasto ha sido agregado correctamente.'); 

 return Redirect::back()->withInput()->withErrors($expense->errors); 

返回某些类型的json对象,指示成功/失败。

然而,

就像我之前说的那样,你的表单能够在没有启用Javascript的情况下提交,所以如果你确实更改了控制器中的那些行,那么你只需要这样做,这样用户只有在提交表单时才会看到json对象。 该问题的答案是在您的控制器中检测提交是否是通过ajax发送的,并适当地格式化响应:

 public function addExpense(){ $expense = new Expense; $data = Input::all(); //$isAjax = Request::ajax(); // It is probably better to use Request::wantsJson() here, since it // relies on the standard Accepts header vs non-standard X-Requested-With // See http://stackoverflow.com/a/28606473/697370 $isAjax = Request::wantsJson(); if ($expense->isValid($data)) { $expense->fill($data); $expense->save(); //Recargar la tabla gastos if($isAjax) { // Return your success JSON here } return Redirect::to('expense/index')->with('success', 'El gasto ha sido agregado correctamente.'); } if($isAjax) { // Return your fail JSON here } return Redirect::back()->withInput()->withErrors($expense->errors); }