gpt4 book ai didi

php - Laravel Ajax 验证

转载 作者:行者123 更新时间:2023-12-05 08:57:50 27 4
gpt4 key购买 nike

我了解如何通过在 Controller 方法中对类名进行类型提示来验证请求。但是对于 Ajax 请求,According to the documentation ,我应该在 Controller 中验证数据,因为使用验证器类将重定向而不是发送响应。

我正在看的主要部分是:

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.

但是,我的 Controller 是这样的:

public function update(App\Permission $permission, Request $request)
{
$this->validate($request, [
'permission_description' => 'required|string'
]);

...
}

而且我终其一生都无法让它用 JSON 进行响应。文档指出,如果失败,它会抛出 Illuminate\Contracts\Validation\ValidationException 异常,但我无法捕获它。

每当它失败时,它总是重定向回编辑页面。显然我不想要这个,我想要 json 响应。

我刚刚尝试用整个 $v = Validator::make($request->all(), ...); 来“手动写出来”,这确实有效,但什么是如果它不起作用,使用 $this->validate() 方法有什么意义?

$this->validate() 方法是否不能与 AJAX 一起使用,而我每次都必须写很长的代码?难道我做错了什么?!

下面是我试过的:

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 **/
}

更新文档不正确。它指出 $this->validate() 方法会抛出一个 Illuminate\Contracts\Validation\ValidationException 但它不会。它抛出一个 Illuminate\Http\Exception\HttpResponseException 异常。

最佳答案

简单地告诉你想要在 header 中使用 json 也应该可以解决这个问题。 Laravel 检查请求是否为 ajax 或是否请求 json。

if ($this->ajax() || $this->wantsJson())
{
return new JsonResponse($errors, 422);
}

解决方案:

添加标题

接受:应用程序/json

关于php - Laravel Ajax 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28858575/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com