首页 文章

Laravel AJAX 验证:返回 HTML 而不是 JSON

提问于
浏览
1

正如文档中所述,如果 AJAX 验证失败,您将获得 json 响应:

如果验证失败,将生成重定向响应以将用户发送回其先前的位置。错误也将闪现到会话中,以便可以显示。如果请求是 AJAX 请求,则将向用户返回具有 422 状态代码的 HTTP 响应,包括验证错误的 JSON 表示。

但我更喜欢局部视图闪烁错误,这是非 AJAX 的默认值。所以是否可以模拟非 AJAX 或关闭 AJAX而无需重建源代码或其他一些尴尬?

BTW,罪魁祸首函数是 buildFailedValidationResponse。

2 回答

  • 2

    这些天我遇到了类似的问题,最后还覆盖了一个方法。

    在 Laravel 5.1.20 下,我不得不将类 Illuminate\Foundation\Http\FormRequest 中的方法响应复制到类 App\Http\Requests\Request 中,就像你的答案一样,改变了

    if ($this->ajax() || $this->wantsJson()) {
    

    if ($this->wantsJson())) {
    

    这是 App\Http\Requests\Request 类中的完整方法

    public function response(array $errors)
    {
        if (!$this->pjax() && ($this->ajax() || $this->wantsJson())) {
            return new JsonResponse($errors, 422);
        }
    
        return $this->redirector->to($this->getRedirectUrl())
                                ->withInput($this->except($this->dontFlash))
                                ->withErrors($errors, $this->errorBag);
    }
    
  • 0

    管理用蛮力解决问题。刚刚覆盖了 AuthController 中的 trait 方法。对此感觉不好。

    protected function buildFailedValidationResponse(Request $request, array $errors) 
    { 
        if (/*$request->ajax() ||*/ $request->wantsJson()) { return new JsonResponse($errors, 422); 
    }
    

相关问题