Laravel 5 Ajax 帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28379023/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:51:46  来源:igfitidea点击:

Laravel 5 Ajax post

ajaxlaravellaravel-5

提问by user4269033

Hi I am really having a hard time on the new structures in laravel 5, I'm trying to submit a form via AJAX post but I keep getting error 422 (Bad Request). Am I missing something or do I need to do something with my Request class? Here is my code:

嗨,我真的很难处理 laravel 5 中的新结构,我正在尝试通过 AJAX 帖子提交表单,但我一直收到错误 422(错误请求)。我是否遗漏了什么,或者我需要对我的 Request 课程做些什么?这是我的代码:

Controller:

控制器:

public function login(LoginRequest $request)
{

    if ($this->auth->attempt($request->only('email', 'password')))
    {
        return redirect("/");
    }

    return response()->json(['errors'=>$request->response]);
}

LoginRequest file (I added a custom response method which is):

LoginRequest 文件(我添加了一个自定义响应方法):

public function response(array $errors)
{
    if ($this->ajax() || $this->wantsJson())
    {
        return response()->json($errors, 422);
    }

    return response()->json($errors);
}

My ajax code:

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

So My problem is that when I submit my form all I can see from my console is - Failed to load resource: the server responded with a status of 422 (Bad Request)

所以我的问题是,当我提交表单时,我可以从控制台看到的是 - 加载资源失败:服务器响应状态为 422(错误请求)

Please if anyone can help. Thanks in advance!

请如果有人可以提供帮助。提前致谢!

采纳答案by thorne51

I was actually just struggling with this myself, and the answer is pretty simple actually.

我实际上只是自己在为此苦苦挣扎,实际上答案非常简单。

Because Laravel's request responds with a status code of 422, jQuery's success/done functions don't fire, but rather the error function, seeing as it's not 200.

因为 Laravel 的请求以 422 的状态码响应,jQuery 的成功/完成函数不会触发,而是错误函数,因为它不是 200。

So, in order to get the JSON response from your AJAX request generated from the Request object due to validation failing, you need to define the error handler, in your case as follows:

因此,为了从由于验证失败而从 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);
    });

回答by Andres Zapata

I had a similar problem, I'll leave here the code that I ended up with.

我有一个类似的问题,我会在这里留下我最终得到的代码。

the form:

表格:

<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>

The jquery:

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

And finally the method of the controller that handles the ajax login request,

最后是处理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');

}