Laravel Ajax响应和处理错误

时间:2015-10-25 20:20:52

标签: php ajax laravel response

这是我的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>

我需要在Laravel 5.1中处理Ajax请求的错误。这是我的处理代码

$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。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:5)

您可能正在尝试在不同级别上工作。假设您没有在ajax脚本中处理错误响应,那么刀片无法知道错误响应,因为html页面是由控制器按原样提供的,并且它不会改变直到下一次刷新。如果你想让刀片知道响应,你需要异步捕获它,即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-errors div才能生效。

答案 1 :(得分:0)

希望对您有帮助

        $.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  
                });
            }
        }); 

答案 2 :(得分:0)

这是更简洁的解决方案。快乐黑客:)

   .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) => {
    
  });