Laravel 5 Ajax post
Laravel 5 Ajax post
您好,我在 laravel 5 中的新结构上遇到了困难,我正在尝试通过 AJAX post 提交表单,但我一直收到错误 422(错误的请求)。我是否遗漏了什么或者我需要对我的请求 class 做些什么?这是我的代码:
控制器:
public function login(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
return redirect("/");
}
return response()->json(['errors'=>$request->response]);
}
LoginRequest 文件(我添加了一个自定义响应方法是):
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson())
{
return response()->json($errors, 422);
}
return response()->json($errors);
}
我的ajax代码:
$("#form-login").submit(function(){
var selector = $(this);
$.ajax({
url: selector.attr("action"),
type: "post",
data: selector.serialize(),
dataType: "json",
}).done(function(data){
console.log(data);
if(data.status == "failed"){
alert("error");
}else{
alert("success");
}
});
return false;
});
所以我的问题是,当我提交表单时,我只能从控制台看到 - 无法加载资源:服务器响应状态为 422(错误请求)
如果有人可以提供帮助,请提供帮助。提前致谢!
其实我自己也在纠结这个问题,答案其实很简单。
因为 Laravel 的请求以状态代码 422 响应,jQuery 的 success/done 函数不会触发,而是错误函数,因为它不是200.
因此,为了从由于验证失败而从 Request 对象生成的 AJAX 请求中获得 JSON 响应,您需要定义错误处理程序,在您的情况下如下:
$.ajax({ /* ... */ })
.done(function(response) { /* ... */ })
.error(function(data) { // the data parameter here is a jqXHR instance
var errors = data.responseJSON;
console.log('server errors',errors);
});
我遇到了类似的问题,我将在此处留下我最终得到的代码。
表格:
<div class="container">
<div class="text-center">
<div class="title">{!!HTML::image("img/HERLOPS_Transparent_Blue.png") !!}</div>
{!! Form::open(['data-remote','url' => '/auth/login', 'class' => 'col-lg-4 col-lg-offset-4', 'id' => 'login_form']) !!}
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email" value="{{ old('email') }}">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Your Password">
</div>
<button id="submit" type="submit" class="btn btn-primary">Login <i class="fa fa-sign-in"></i></button>
<div style="clear:both">
<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
</div>
{!! Form::close() !!}
<div style="text-align:center" class="col-lg-4 col-lg-offset-4" id="form-errors"></div>
<div style="clear:both"></div>
<div class="quote">{{ Inspiring::quote() }}</div>
</div>
</div>
jquery:
(function() {
var submitAjaxRequest = function(e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST'; //Laravel Form::open() creates an input with name _method
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(NULL, NULL, jqXHR) {
if(jqXHR.status === 200 ) {//redirect if authenticated user.
$( location ).prop( 'pathname', 'projects' );
console.log(data);
}
},
error: function(data) {
if( data.status === 401 ) {//redirect if not authenticated user
$( location ).prop( 'pathname', 'auth/login' );
var errors = data.responseJSON.msg;
errorsHtml = '<div class="alert alert-danger">'+errors+'</div>';
$( '#form-errors' ).html( errorsHtml );
}
if( data.status === 422 ) {
//process validation errors here.
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors , function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></di>';
$( '#form-errors' ).html( errorsHtml );
} else {
}
}
});
e.preventDefault();
};
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
最后是处理 ajax 登录请求的控制器方法,
/**
* Handle an ajax login request to the application
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);// Returns response with validation errors if any, and 422 Status Code (Unprocessable Entity)
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials))
{
return response(['msg' => 'Login Successfull'], 200) // 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
return response(['msg' => $this->getFailedLoginMessage()], 401) // 401 Status Code: Forbidden, needs authentication
->header('Content-Type', 'application/json');
}
您好,我在 laravel 5 中的新结构上遇到了困难,我正在尝试通过 AJAX post 提交表单,但我一直收到错误 422(错误的请求)。我是否遗漏了什么或者我需要对我的请求 class 做些什么?这是我的代码:
控制器:
public function login(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
return redirect("/");
}
return response()->json(['errors'=>$request->response]);
}
LoginRequest 文件(我添加了一个自定义响应方法是):
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson())
{
return response()->json($errors, 422);
}
return response()->json($errors);
}
我的ajax代码:
$("#form-login").submit(function(){
var selector = $(this);
$.ajax({
url: selector.attr("action"),
type: "post",
data: selector.serialize(),
dataType: "json",
}).done(function(data){
console.log(data);
if(data.status == "failed"){
alert("error");
}else{
alert("success");
}
});
return false;
});
所以我的问题是,当我提交表单时,我只能从控制台看到 - 无法加载资源:服务器响应状态为 422(错误请求)
如果有人可以提供帮助,请提供帮助。提前致谢!
其实我自己也在纠结这个问题,答案其实很简单。
因为 Laravel 的请求以状态代码 422 响应,jQuery 的 success/done 函数不会触发,而是错误函数,因为它不是200.
因此,为了从由于验证失败而从 Request 对象生成的 AJAX 请求中获得 JSON 响应,您需要定义错误处理程序,在您的情况下如下:
$.ajax({ /* ... */ })
.done(function(response) { /* ... */ })
.error(function(data) { // the data parameter here is a jqXHR instance
var errors = data.responseJSON;
console.log('server errors',errors);
});
我遇到了类似的问题,我将在此处留下我最终得到的代码。
表格:
<div class="container">
<div class="text-center">
<div class="title">{!!HTML::image("img/HERLOPS_Transparent_Blue.png") !!}</div>
{!! Form::open(['data-remote','url' => '/auth/login', 'class' => 'col-lg-4 col-lg-offset-4', 'id' => 'login_form']) !!}
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email" value="{{ old('email') }}">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Your Password">
</div>
<button id="submit" type="submit" class="btn btn-primary">Login <i class="fa fa-sign-in"></i></button>
<div style="clear:both">
<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
</div>
{!! Form::close() !!}
<div style="text-align:center" class="col-lg-4 col-lg-offset-4" id="form-errors"></div>
<div style="clear:both"></div>
<div class="quote">{{ Inspiring::quote() }}</div>
</div>
</div>
jquery:
(function() {
var submitAjaxRequest = function(e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST'; //Laravel Form::open() creates an input with name _method
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(NULL, NULL, jqXHR) {
if(jqXHR.status === 200 ) {//redirect if authenticated user.
$( location ).prop( 'pathname', 'projects' );
console.log(data);
}
},
error: function(data) {
if( data.status === 401 ) {//redirect if not authenticated user
$( location ).prop( 'pathname', 'auth/login' );
var errors = data.responseJSON.msg;
errorsHtml = '<div class="alert alert-danger">'+errors+'</div>';
$( '#form-errors' ).html( errorsHtml );
}
if( data.status === 422 ) {
//process validation errors here.
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors , function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></di>';
$( '#form-errors' ).html( errorsHtml );
} else {
}
}
});
e.preventDefault();
};
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
最后是处理 ajax 登录请求的控制器方法,
/**
* Handle an ajax login request to the application
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);// Returns response with validation errors if any, and 422 Status Code (Unprocessable Entity)
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials))
{
return response(['msg' => 'Login Successfull'], 200) // 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
return response(['msg' => $this->getFailedLoginMessage()], 401) // 401 Status Code: Forbidden, needs authentication
->header('Content-Type', 'application/json');
}