如何使用$阿贾克斯();在laravel功能 [英] How to use $.ajax(); function in laravel

查看:140
本文介绍了如何使用$阿贾克斯();在laravel功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过AJAX添加新的对象,但我不知道如何使用$阿贾克斯()函数laravel。

I need add new object via ajax, but I don't know how to use $.ajax() function in laravel.

我的刀片templete的形式是:

My form in blade templete is:

{{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()}}

我的code控制器是:

My code in the controller is:

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

this is my function 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

Thanks for help! :D

推荐答案

您需要改变你的Ajax请求,并添加URL中的POST数据提交到:

You need to change your ajax request and add a URL in which to submit the POST data to:

$.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 函数接受事件对象作为参数,这样就可以取消的默认操作时,单击该按钮:

It looks like you built the form so that it would also accommodate non-javascript submissions. That's great, however, when you click the button not only will the ajax request get sent off, but the form will be submitted. Change your submitExpenses function to accept the event object as a parameter so that you can cancel the default action when you click the button:

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

一件事

当您提交通过AJAX请求,您会收到回一个响应。在你的控制器,你实际上是将用户重定向,你不想做的发出Ajax请求时。在你的要求你指定你想要一些返回的数据将被发送回你JSON格式。你需要在你的控制器改变这些行:

When you submit a request via ajax, you'll receive a response back. In your controller you're actually redirecting the user, which you don't want to do when issuing an ajax request. In your request you're specifying that you want some return data to be sent back to you in json format. You need to change these lines in your controller:

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

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

要返回某种类型的JSON对象的指示成功/失败。

To return some type of json object indicating success/failure.

但是,

就像我说你的表格前,能够被提交不使用Javascript功能,所以如果你不改变你的控制器的线你就得说得那么这些用户将只能看到JSON对象时,他们提交表单。这个问题的答案的问题是要在您的控制器适当地检测通过AJAX提交是否被发送或没有,然后格式化响应:

Like I said before, your form is capable of being submitted without Javascript enabled, so if you do change those lines in your controller you'll just have made it so those users will only see the json objects whenever they submit the form. The answer to that issue is to detect in your controller whether or not the submission was sent via ajax or not, and format the response appropriately:

public function addExpense(){
    $expense = new Expense;
    $data = Input::all();
    $isAjax = Request::ajax();

    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);
}

这篇关于如何使用$阿贾克斯();在laravel功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆