Javascript 如何使用ajax在laravel 5中发布表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32467626/
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 do I post a form in laravel 5 using ajax?
提问by Hymanjoesmith
I'm having a ton of trouble learning how to make an ajax post in laravel. I want to be able to show errors using jquery after validation but I have no idea how to access the object sent to my controller; so I dont even know what to 'return' in the controller. Can someone please walk me through this?
我在学习如何在 laravel 中制作 ajax 帖子时遇到了很多麻烦。我希望能够在验证后使用 jquery 显示错误,但我不知道如何访问发送到我的控制器的对象;所以我什至不知道在控制器中“返回”什么。有人可以引导我完成这个吗?
This is a part of my view
这是我观点的一部分
<meta name="_token" content="{{ csrf_token() }}" />
<div class='row'>
{!! Form::open(['url'=>'register','id'=>'sign-up','class'=>'col-md-6 col-md-push-4 form-horizontal'])!!}
<div class='form-group'>
{!! Form::label('first_name', 'First Name:',['class'=>'col-xs-12 col-md-3']) !!}
<div class= 'col-xs-12 col-md-6'>
{!! Form::text('first_name', null, ['class' => 'form-control'])!!}
</div>
</div>
<div class='form-group'>
{!! Form::label('last_name', 'Last Name:',['class'=>'col-xs-12 col-md-3']) !!}
<div class= 'col-xs-12 col-md-6'>
{!! Form::text('last_name', null, ['class' => 'form-control'])!!}
</div>
</div>
<div class='form-group'>
{!! Form::label('email', 'Email Address:',['class'=>'col-xs-12 col-md-3']) !!}
<div class= 'col-xs-12 col-md-6 '>
{!! Form::text('email', null, ['class' => 'form-control'])!!}
<div class='form-group'>
{!! Form::label('password', 'Password:',['class'=>'col-xs-12 col-md-3']) !!}
<div class= 'col-xs-12 col-md-6'>
{!! Form::password('password', null, ['class' => 'form-control'])!!}
</div>
</div>
<div class='form-group'>
{!! Form::label('password_confirmation', 'Confirm Password:',['class'=>'col-xs-12 col-md-3']) !!}
<div class= 'col-xs-12 col-md-6'>
{!! Form::password('password_confirmation', null, ['class' => 'form-control'])!!}
</div>
</div>
</div> <div class='btn btn-small'>
{!! Form::submit('Join Us!',['class'=>'btn btn-success btn-sm form-control'])!!}
</div>
{!! Form::close() !!}
</div>
.js file:
.js 文件:
$(function(){
$('#sign-up').on('submit',function(e){
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
e.preventDefault(e);
$.ajax({
type:"POST",
url:'/register',
data:$(this).serialize(),
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
}
})
});
});
controller:
控制器:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CreateRegisterRequest;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\HttpResponse;
use Input;
class UserController extends Controller
{
public function create(CreateRegisterRequest $request)
{
}
public function show()
{
return view('user.profile');
}
}
Form Request:
表格请求:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateRegisterRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'first_name' =>'required',
'last_name'=>'required',
'url'=>'url',
'description',
'email'=>'unique:users,email|email',
'password'=>'min:6|confirmed',
'password_confirmation'=>'min:6'
];
}
}
回答by samrap
Without looking at any of your code, I can tell you my way of performing this task. There may be other ways, but this is generally how I have approached it since I started using Laravel.
无需查看您的任何代码,我就可以告诉您我执行此任务的方式。可能还有其他方法,但这通常是我开始使用 Laravel 以来的方法。
I want to be able to show errors using jquery after validation but I have no idea how to access the object sent to my controller; so I dont even know what to 'return' in the controller.
我希望能够在验证后使用 jquery 显示错误,但我不知道如何访问发送到我的控制器的对象;所以我什至不知道在控制器中“返回”什么。
Let's start by breaking this down into 3 simpler questions.
让我们首先将其分解为 3 个更简单的问题。
1. How do I access the object sent tomy controller?
1. 如何访问发送到我的控制器的对象?
Well, in your AJAX you can choose to send a GET or POST request. Convention states that you should use POST for updating the model and GET for retrieving from the model. If you are using REST, then you have other methods to make use of (PUT, PATCH, DELETE, etc). You can learn more about these on your own, but for the sake of this answer I will keep things simple with just GET and POST.
好吧,在您的 AJAX 中,您可以选择发送 GET 或 POST 请求。约定规定您应该使用 POST 来更新模型,并使用 GET 从模型中检索。如果您使用 REST,那么您可以使用其他方法(PUT、PATCH、DELETE 等)。你可以自己了解更多关于这些的信息,但为了这个答案,我将只使用 GET 和 POST 来保持简单。
In your example you use POST, so let's go with that. You already called the JQuery serialize
method, so that's all you need to do. In your Laravel controller, simply take the argument Request $request
for the method, and the Laravel method $request->input()
will give you a key/value array of all the parameters sent in the request. You can then handle them accordingly.
在您的示例中,您使用 POST,所以让我们继续。您已经调用了 JQueryserialize
方法,这就是您需要做的全部工作。在你的 Laravel 控制器中,简单地获取Request $request
方法的参数,Laravel 方法$request->input()
会给你一个包含请求中发送的所有参数的键/值数组。然后,您可以相应地处理它们。
2. What should I return in the controller?
2. 我应该在控制器中返回什么?
Typically you return JSON data for an AJAX request. It is easy to parse, and both JavaScript and JQuery have nice objects for parsing JSON for you.
通常,您会为 AJAX 请求返回 JSON 数据。它很容易解析,JavaScript 和 JQuery 都有很好的对象来为您解析 JSON。
In your Laravel controller, you can add the following line at the end of your method to return some JSON:
在 Laravel 控制器中,您可以在方法末尾添加以下行以返回一些 JSON:
return response()->json($data);
In this example, $data
is an array containing the JSON you want to return. In PHP, we can represent a JSON string as an array of key/valuepairs, like so:
在此示例中,$data
是一个包含要返回的 JSON 的数组。在 PHP 中,我们可以将 JSON 字符串表示为键/值对数组,如下所示:
$data = [
'success': true,
'message': 'Your AJAX processed correctly'
];
Typically, if this were a plain old PHP script, we would have to call PHP's json_encodefunction, but Laravel handles this for us, so all we need to do is pass the array. For debugging purposes, you may want to make use of the JSON_PRETTY_PRINT
constant, which will output the JSON nicely on the screen if you access the URL directly:
通常,如果这是一个普通的旧 PHP 脚本,我们将不得不调用 PHP 的json_encode函数,但 Laravel 会为我们处理这个,所以我们需要做的就是传递数组。出于调试目的,您可能希望使用JSON_PRETTY_PRINT
常量,如果您直接访问 URL,它将在屏幕上很好地输出 JSON:
return response()->json($data, 200, [], JSON_PRETTY_PRINT);
3. How do I access the object sentfrom my controller?
3. 如何访问我的控制器发送的对象?
Well, now that your response is a simple JSON string, you can use any of the built in JavaScript methods for parsing the JSON. I typically use JSON.parse(json)
, where json
is your JSON string returned by the controller. See herefor more details.
好吧,既然您的响应是一个简单的 JSON 字符串,您就可以使用任何内置的 JavaScript 方法来解析 JSON。我通常使用JSON.parse(json)
,json
控制器返回的 JSON 字符串在哪里。请参阅此处了解更多详情。
4. So, how do I get this data?
4. 那么,我如何获得这些数据?
Well, it looks like you probably already have this figured out, but just to be sure I will clarify. You need to register the route to your controller. Then, you can simply call that URI using the JQuery AJAX object and then the injected variable data
will be whatever was returned from the controller, in this case a JSON string.
好吧,看起来您可能已经弄清楚了这一点,但为了确保我会澄清。您需要将路由注册到您的控制器。然后,您可以简单地使用 JQuery AJAX 对象调用该 URI,然后注入的变量data
将是从控制器返回的任何内容,在本例中为 JSON 字符串。