【问题标题】:Laravel Ajax Response And Handling ErrorsLaravel Ajax 响应和处理错误
【发布时间】:2016-01-24 21:31:32
【问题描述】:

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

【问题讨论】:

    标签: php ajax laravel response


    【解决方案1】:

    您可能正在尝试在不同的层次上工作。假设您没有在 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 才能使用。

    【讨论】:

    • '
    • '+ 值[0] + '
    • ';你为什么喜欢那个?我认为我们需要价值[key]
  • @CihanKüsmez 是的,key 如果您遇到多个错误。我确实指定它只显示一个错误,我相信这完全符合您的需求。
  • $.each(data, function(key, value) { 应该是 $.each(errors.errors, function(key, value) {
  • 【解决方案2】:

    希望对你有帮助

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

    【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签