php - laravel5.4通过ajax提交表单获取到422返回,ajax无法捕获返回内容
本文介绍了php - laravel5.4通过ajax提交表单获取到422返回,ajax无法捕获返回内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
1.通过ajax提交表单,如果验证不通过,则会返回http状态值为422的json
2.该json的格式如何自定义?
3.http状态值422,貌似已经在框架里面写死了。我想通过捕获验证异常的形式返回自定义的json到前端,这个能实现吗?
4.利用jquery的ajax方法在error的时候还是拿不到格式化成json对象的的返回数据,只能拿到一个字符串形式的json
解决方案
json格式这个自己根据需要定义,没有什么多说的,后面两个问题
-
http状态值422,貌似已经在框架里面写死了。我想通过捕获验证异常的形式返回自定义的json到前端,这个能实现吗?
<?php namespace App\Exceptions; use Illuminate\Validation\ValidationException; ... class Handler extends ExceptionHandler { ... public function render($request, Exception $e) { if ($request->ajax() || $request->wantsJson()) { $errors = []; if ($e instanceof ValidationException && $e->getResponse()) { try { $errors = json_decode($e->getResponse()->getContent(), true); } catch (\Exception $ex) { $errors = $e->getResponse()->getContent(); } } return response()->json([ 'message' => empty($errors) ? (empty($e->getMessage()) ? '出错了' : $e->getMessage()) : implode(',', array_first($errors)), 'status_code' => $e->getStatusCode(), 'errors' => $errors ]); } ... } }
-
利用jquery的ajax方法在error的时候还是拿不到格式化成json对象的的返回数据,只能拿到一个字符串形式的json
$.ajax({ ... dataType: "json", ...
这篇关于php - laravel5.4通过ajax提交表单获取到422返回,ajax无法捕获返回内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文