没有通过AJAX获得laravel验证的确切错误消息

时间:2018-10-22 23:40:41

标签: javascript php ajax laravel

我在laravel中收到的消息是:

{message: "The given data was invalid.", errors: {oData: 
["validation.required"]}}
errors: {oData: ["validation.required"]}
message: "The given data was invalid."

不是消息本身,而是validation.required消息。 当我将其附加到HTML时,它将显示“ validation.required”,而不是laravel提供的错误消息。

$.ajax({    
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: oParams['sUrl'],
        type: oParams['sType'],
        data: oParams['oData'],
        contentType: oParams['mContentType'],    
        processData: oParams['mProcessData'],
        success: function(aData)
        {
            console.log(aData);
        },
        error: function(request, status, error)
        {
            json = $.parseJSON(request.responseText);
            $.each(json.errors, function(key, value){
                $('.alert-danger').show();
                $('.alert-danger').append('<p>'+value+'</p>');
            });
            $("#result").html('')
        }          
    });

    //Controller
    public function addUser(Request $oRequest)
    {
    $aValidated = $oRequest->validate([
        'oData' => 'required',
    ]);
    return $aValidated;
    }

1 个答案:

答案 0 :(得分:0)

问题是您正在errors对象上运行,该对象确实具有一个键,该键具有包含字符串validation.required的数组。相反,您应该做的是这样的:

json = $.parseJSON(request.responseText);
        $.each(json, function(element){
            $('.alert-danger').show();
            $('.alert-danger').append('<p>'+ element.message +'</p>');
        });
        $("#result").html('')