我需要通过 ajax 添加新对象,但我不知道如何在 laravel 中使用 $.ajax() 函数。
我在刀片模板中的形式是:
{{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)}}
<br />
{{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