Laravel Ajax 响应和错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33334644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:34:25  来源:igfitidea点击:

Laravel Ajax Response And Handling Errors

phpajaxlaravelresponse

提问by Cihan Küsmez

Here is a part of my html file.

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

I need to handle errors with Ajax Request in Laravel 5.1. Here is my code for handling

我需要处理 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);
        }

    }

Console Message

控制台消息

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

I can see errors in console but. In Blade i cannot reach $errors. How can i fix the problem ?

我可以在控制台中看到错误但是。在 Blade 中,我无法达到 $errors。我该如何解决这个问题?

回答by MisterP

You are probably trying to work on different levels. Assuming that you are not handling the error response in your ajax script, there's no way for blade to know the error response, since the html page is provided by the controller as-is and it won't change until the next refresh. If you want to let blade know the response, you need to catch it asynchronously, that is ajax level.
Assuming again you are POSTing with a standard ajax request, you could do something like:

您可能正在尝试在不同的级别上工作。假设您没有在 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  
                });
            }
        });  

Note that you will need a #form-errorsdiv inside your posting form for this to work.

请注意,您需要#form-errors在发布表单中添加一个div 才能使其工作。

回答by meduprise

Hope that will help you

希望能帮到你

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