如何使用 $.ajax(); Laravel 中的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22414632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use $.ajax(); function in laravel
提问by Emiliano
I need add new object via ajax, but I don't know how to use $.ajax() function in laravel.
我需要通过ajax添加新对象,但我不知道如何在laravel中使用$.ajax()函数。
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()}}
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);
}
And my js is:
我的js是:
$("#btnSubmit").click(submitExpenses);
this is my function 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...');
}
});
});
};
Thanks for help! :D
感谢帮助!:D
回答by Jeff Lambert
You need to change your ajax request and add a URL in which to submit the POST data to:
您需要更改您的 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...');
}
});
But thats not all
但这还不是全部
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:
看起来您构建了表单,以便它也可以容纳非 javascript 提交。这很好,但是,当您单击按钮时,不仅会发送 ajax 请求,还会提交表单。更改您的submitExpenses
函数以接受事件对象作为参数,以便您可以在单击按钮时取消默认操作:
var submitExpenses = function(e){
e.preventDefault();
...
One more thing
还有一件事
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:
当您通过 ajax 提交请求时,您将收到回复。在您的控制器中,您实际上是在重定向用户,而在发出 ajax 请求时您不想这样做。在您的请求中,您指定要以 json 格式将一些返回数据发送回给您。您需要在控制器中更改这些行:
return Redirect::to('expense/index')->with('success', 'El gasto ha sido agregado correctamente.');
and
和
return Redirect::back()->withInput()->withErrors($expense->errors);
To return some type of json object indicating success/failure.
返回某种类型的 json 对象,指示成功/失败。
However,
然而,
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:
就像我之前说的那样,您的表单可以在不启用 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);
}