Laravel Ajax响应和错误处理


Laravel Ajax Response And Handling Errors

这是我的html文件的一部分

<div class="form-group{{ $errors->has('address_name') ? ' has-error' : '' }}">
    <label for="address_name">{{ trans('address.address_name') }} <span class="required_field">*</span></label>
    <input name="address_name" type="text" class="form-control" id="address_name" placeholder="{{ trans('address.address_name_placeholder') }}" maxlength="30">
    @if($errors->has('address_name'))
        <span class="help-block">{{ $errors->first('address_name') }}</span>
    @endif
</div>

我需要处理错误的Ajax请求在Laravel 5.1。下面是我处理

的代码
$validator = Validator::make($addressData, $this->rules());
    if ($validator->fails())
    {
        return response()->json([
            'success' => 'false',
            'errors'  => $validator->errors()->all(),
        ], 400);
    }
    else
    {
        //Save Address
        try
        {
            $this->insertAddress($addressData);
            return response()->json(['success' => true], 200);
        }
        catch(Exception $e)
        {
            return response()->json([
                'success' => 'false',
                'errors'  => $e->getMessage(),
            ], 400);
        }
    }

控制台消息

{"success":"false","errors":["The Address Name field is required.","The Recipient field is required.","The Address field is required."]}

我可以在控制台看到错误,但是。在Blade中,我无法达到$errors。

您可能正在尝试在不同的级别上工作。假设您没有在ajax脚本中处理错误响应,那么blade就无法知道错误响应,因为html页面是由控制器按原样提供的,直到下一次刷新时才会更改。如果你想让blade知道响应,你需要异步捕获它,这是ajax级别的。再次假设您正在使用标准ajax请求进行post,您可以这样做:

    var form = $('#your-form-id');
        $.ajax({
            url: form.attr( 'action' ),
            type: 'POST',
            data: form.serialize(),
            success: function(data){
                // Successful POST
                // do whatever you want
            },
            error: function(data){
                // Something went wrong
                // HERE you can handle asynchronously the response 
                // Log in the console
                var errors = data.responseJSON;
                console.log(errors);
                // or, what you are trying to achieve
                // render the response via js, pushing the error in your 
                // blade page
                 errorsHtml = '<div class="alert alert-danger"><ul>';
                 $.each( errors.error, function( key, value ) {
                      errorsHtml += '<li>'+ value[0] + '</li>'; //showing only the first error.
                 });
                 errorsHtml += '</ul></div>';
                 $( '#form-errors' ).html( errorsHtml ); //appending to a <div id="form-errors"></div> inside form  
                });
            }
        });  

请注意,您将需要在您的发布表单中的#form-errorsdiv工作

希望对你有帮助

        $.ajax({
            url: form.attr( 'action' ),
            type: 'POST',
            data: form.serialize(),
            success: function(data){
                // do whatever you want
            },
            error: function(data){
                // Log in the console
                var errors = data.responseJSON;
                console.log(errors);
                // or, what you are trying to achieve
                // render the response via js, pushing the error in your 
                // blade page
                    var errors = response.responseJSON;
                   errorsHtml = '<div class="alert alert-danger"><ul>';
                  $.each(errors.errors,function (k,v) {
                         errorsHtml += '<li>'+ v + '</li>';
                  });
                  errorsHtml += '</ul></di>';
                  $( '#error_message' ).html( errorsHtml );
                   //appending to a <div id="error_message"></div> inside your form  
                });
            }
        }); 

这里有一个更简洁的解决方案。快乐的黑客:)

   .fail((err) => {     
    let allErrors = Object.values(err.responseJSON)
    .map(el => (
      el = `<li>${el}</li>`
    ))
    .reduce((next, prev) => ( next = prev + next ));   
    const setErrors = `
      <div class="alert alert-danger" role="alert">
          <ul>${allErrors}</ul>
      </div>
    `;
    $('.modalErrorr').html(setErrors);
  })       
  .always((data) => {
    
  });