Laravel 5阿贾克斯后 [英] Laravel 5 Ajax post

查看:176
本文介绍了Laravel 5阿贾克斯后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我真的很不好受在laravel 5新的结构,我想通过AJAX提交后一个形式,但我不断收到错误422(错误请求)。我失去了一些东西还是我需要做一些与我的要求类?这是我的code:

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:

控制器:

public function login(LoginRequest $request)
{

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

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

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

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

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

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

我的阿贾克斯code:

My ajax code:

$("#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状态(错误的请求)

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)

请,如果有人可以提供帮助。在此先感谢!

Please if anyone can help. Thanks in advance!

推荐答案

我其实只是用这种挣扎自己,答案是pretty的简单实际。

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

由于Laravel的请求以422状态code,jQuery的成功/完成的功能不火,而误差函数,看到它不是200。

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.

因此​​,为了得到从Request对象中产生,由于验证失败的AJAX请求的JSON响应,您需要定义错误处理程序,在您的情况如下:

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:

$.ajax({ /* ... */ })
    .done(function(response) { /* ... */ })
    .error(function(data) { // the data parameter here is a jqXHR instance
        var errors = data.responseJSON;
        console.log('server errors',errors);
    });

这篇关于Laravel 5阿贾克斯后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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