Laravel Ajax 验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28858575/
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
Laravel Ajax validation
提问by Phil Cross
I understand how to validate requests by type-hinting the class name in the controller method. However for Ajax requests, According to the documentation, I should validate data in the controller, because using a validator class will redirect rather than send a response.
我了解如何通过在控制器方法中键入提示类名来验证请求。但是对于 Ajax 请求,根据文档,我应该验证控制器中的数据,因为使用验证器类将重定向而不是发送响应。
The main part I'm looking at is this:
我正在看的主要部分是这样的:
If the incoming request was an AJAX request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors.
如果传入请求是 AJAX 请求,则不会生成重定向。相反,带有 422 状态代码的 HTTP 响应将返回到浏览器,其中包含验证错误的 JSON 表示。
However, my controller is as follows:
但是,我的控制器如下:
public function update(App\Permission $permission, Request $request)
{
$this->validate($request, [
'permission_description' => 'required|string'
]);
...
}
And I can't for the life of me get it to respond with JSON. The documentation states that if it fails, it throws an Illuminate\Contracts\Validation\ValidationException
exception, but I can't catch it.
而且我这辈子都无法让它用 JSON 响应。文档指出,如果失败,则会引发Illuminate\Contracts\Validation\ValidationException
异常,但我无法捕获它。
Whenever it fails, it always redirects back to the edit page. Obviously I don't want this, I want the json response.
每当失败时,它总是重定向回编辑页面。显然我不想要这个,我想要json响应。
I have just tried "manually writing it out" with the whole $v = Validator::make($request->all(), ...);
which does work, but what's the point in using the $this->validate()
way if it doesn't work?
我刚刚尝试了“手动写出”的整体$v = Validator::make($request->all(), ...);
工作,但$this->validate()
如果它不起作用,使用这种方式有什么意义?
Does the $this->validate()
method just not work with AJAX and I have to write it the long way each time? Am I doing something wrong?!
该$this->validate()
方法是否不适用于 AJAX,我每次都必须写很长的路?难道我做错了什么?!
Below is what I've tried:
以下是我尝试过的:
public function update(App\Permission $permission, UpdatePermissionRequest $request)
{
/** Redirects rather than returns JSON if the validation fails **/
}
----------------------------------
public function update(App\Permission $permission, Request $request)
{
$this->validate($request, [
'permission_description' => 'required|string'
]);
/** AND I've also tried: **/
try {
$this->validate($request, ['permission_description' => 'required|string']);
} catch (\Illuminate\Contracts\Validation\ValidationException $e {
echo $e; /** Echoing for debug reasons **/
exit;
}
...
/** Still redirects the browser, even if it is an AJAX request **/
}
-----------------------------------------
use Validator;
...
public function update(App\Permission $permission, Request $request)
{
$v = Validator::make($request->all(), [
'permission_description' => 'required|string'
]);
if($v->fails())
{
return response()->json(['reply' => false]);
}
/** Works **/
}
UPDATEThe documentation is incorrect. It states that the $this->validate()
method throws a Illuminate\Contracts\Validation\ValidationException
but it doesn't. It throws a Illuminate\Http\Exception\HttpResponseException
exception.
更新文档不正确。它指出该$this->validate()
方法抛出 aIlluminate\Contracts\Validation\ValidationException
但它没有。它抛出Illuminate\Http\Exception\HttpResponseException
异常。
回答by Filip Holmberg
Simply telling that you want json in the header should also fix this. Laravel checks if the request is ajax of if json is requested.
简单地告诉你想要在标题中使用 json 也应该解决这个问题。Laravel 检查请求是 ajax 还是 json 请求。
if ($this->ajax() || $this->wantsJson())
{
return new JsonResponse($errors, 422);
}
Solution:
解决方案:
Add header
添加标题
Accept: application/json
接受:应用程序/json
回答by Phil Cross
Ok, so it looks like there were 2 contributing factors.
好的,看起来有两个影响因素。
The reason it was redirecting instead of responding with JSON is because the X-Requested-With field wasn't set on the AJAX request. This the AJAX wrapper for the application was setup to deal with Cross Domain requests, which seems to strip out the X-Requested-With field, which makes the ultimate request look non-ajax to the server - hence the redirection.
The reason why it wasn't catching the
Illuminate\Contracts\Validation\ValidationException
exception is because that exception is not thrown. If you open upIlluminate\Foundation\Validation\ValidatesRequest.php
, and search for the functionthrowValidationException()
, it actually throws aHttpResponseException
instead. I attempted to catch theHttpResponseException
and it was caught successfully - I assume the documentation is wrong.
它重定向而不是响应 JSON 的原因是因为 X-Requested-With 字段未在 AJAX 请求中设置。这个应用程序的 AJAX 包装器被设置为处理跨域请求,这似乎去掉了 X-Requested-With 字段,这使得最终请求看起来对服务器来说是非 ajax - 因此重定向。
它没有捕获
Illuminate\Contracts\Validation\ValidationException
异常的原因是因为没有抛出该异常。如果您打开Illuminate\Foundation\Validation\ValidatesRequest.php
并搜索函数throwValidationException()
,它实际上会抛出 aHttpResponseException
。我试图捕捉HttpResponseException
它并成功捕捉到- 我认为文档是错误的。
The solution was to either remove the cross domain attributes on the ajax request, add the X-Requested-With header manually, as per the answer in this post. This would make the application see that it was an AJAX request.
解决方案是删除 ajax 请求上的跨域属性,手动添加 X-Requested-With 标头,根据这篇文章中的答案。这将使应用程序看到它是一个 AJAX 请求。
And if you wanted to manually catch the exception, you need to catch the HttpResponseException
, not the ValidationException
.
如果您想手动捕获异常,则需要捕获 . 而HttpResponseException
不是ValidationException
.
回答by Laurence
Your statement that the docs say it is best to validate AJAX requests in the controller is simply incorrect.
您关于文档说最好在控制器中验证 AJAX 请求的说法是不正确的。
If you scroll a bit further down from what you linked- you'll see this under the FormValidation section
如果您从链接的内容向下滚动一点- 您将在 FormValidation 部分下看到这一点
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
如果验证失败,将生成重定向响应以将用户发送回他们之前的位置。错误也将闪现到会话中,以便它们可供显示。如果请求是 AJAX 请求,则会向用户返回带有 422 状态代码的 HTTP 响应,其中包括验证错误的 JSON 表示。
In other words - there is no reason you cannot do this in a simple FormRequest and simply your code significantly. It will automatically handle the fact it is an AJAX call and return the appropriate HTTP responses.
换句话说 - 你没有理由不能在一个简单的 FormRequest 和你的代码中做到这一点。它将自动处理它是 AJAX 调用的事实并返回适当的 HTTP 响应。
I do this all the time in my L5 apps - it works flawlessly.
我一直在我的 L5 应用程序中这样做 - 它完美无缺。