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

Emi*_*ano 5 javascript php ajax jquery laravel

我需要通过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()}}
Run Code Online (Sandbox Code Playgroud)

我在控制器中的代码是:

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);
}
Run Code Online (Sandbox Code Playgroud)

我的js是:

$("#btnSubmit").click(submitExpenses);
Run Code Online (Sandbox Code Playgroud)

这是我的函数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...');
                }
            });
        });
    };
Run Code Online (Sandbox Code Playgroud)

感谢帮助!:d

Jef*_*ert 11

您需要更改ajax请求并添加用于将POST数据提交到的URL:

$.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...');
    }
});
Run Code Online (Sandbox Code Playgroud)

但那不是全部

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

var submitExpenses = function(e){
    e.preventDefault();
    ...
Run Code Online (Sandbox Code Playgroud)

还有一件事

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

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

return Redirect::back()->withInput()->withErrors($expense->errors);
Run Code Online (Sandbox Code Playgroud)

返回某种类型的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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我会使用`$ isAjax = Request :: ajax();`只是为了保持Laravel'ish的东西 (2认同)