search

Home  >  Q&A  >  body text

php - laravel5.4 gets a 422 return when submitting the form through ajax, and ajax cannot capture the return content

1. Submit the form through ajax. If the verification fails, a json with an http status value of 422 will be returned.
2. How to customize the format of the json?
3. The http status value is 422, which seems to have been hard-coded in the framework. I want to return custom json to the front end by catching validation exceptions. Is this possible?
4. When using the ajax method of jquery, you still cannot get the return data formatted as a json object when an error occurs. You can only get a json in the form of a string

PHP中文网PHP中文网2753 days ago713

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-06-21 10:12:48

    You can define the json format by yourself according to your needs. There is nothing more to say about the next two questions

    • The http status value is 422, which seems to be hard-coded in the framework. I want to return custom json to the front end by catching validation exceptions. Is this possible?

      <?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
                  ]);
              }
              ...
          }
      }
    • Using jquery's ajax method, when an error occurs, you still cannot get the return data formatted as a json object, you can only get a json in the form of a string

      $.ajax({
          ...
          dataType: "json",
          ...

    reply
    0
  • Cancelreply