处理Ajax中的错误返回未定义

时间:2019-02-21 02:28:55

标签: javascript jquery ajax

当Ajax失败时,我试图显示错误,但是我无法深入研究结果来显示确切的错误。

样本

这是我在网络标签playground

中看到的内容
{"message":"The given data was invalid.","errors":{"title":["The title field is required."],"slug":["The slug field is required."]}}

JSON

message The given data was invalid.
errors  {…}
title   […]
0   The title field is required.
slug    […]
0   The slug field is required.

Console

message
The given data was invalid.
errors
{…}
slug: Array [ "The slug field is required." ]
title: Array [ "The title field is required." ]
<prototype>: Object { … }

我能看到的是这样的:

message - The given data was invalid.
errors - [object Object]

代码

error:function(data){
    if( data.status === 422 ) {
        var errors = data.responseJSON;
        errorsHtml = '<div class="alert alert-danger"><ul>';
        $.each( errors , function( key, value ) {
            console.log(key);
            console.log(value);
            errorsHtml += '<li><b>' + key + '</b> - ' + value + '</li>';
        });
        errorsHtml += '</ul></div>';
        $( '#form-errors' ).html( errorsHtml );
    } else if( data.status === 500 ){
        var errors = data.responseJSON;
        $( '#form-errors' ).append(errors.message);
    } else {
        var errors = data.responseJSON;
        $( '#form-errors' ).append(errors.message);
    }
}

我想要的

我想从key部分获得valueerrors

问题

根据我上面的代码,如果我第二次value循环,

//basic
$.each( errors , function( key, value ) {
  //second time loop to get into errors
  $.each( value , function( df, er ) {
    console.log(df);
    console.log(er);
  });
  errorsHtml += '<li><b>' + key + '</b> - ' + value + '</li>';
});

这不起作用。

问题

如何将我的错误部分归还并退回keyvalue

1 个答案:

答案 0 :(得分:0)

您从errors分配的data.responseJSON变量包含您在操场上看到的值。

{"message":"The given data was invalid.","errors":{"title":["The title field is required."],"slug":["The slug field is required."]}}

您可以遍历此对象并直接访问该对象的errors属性。请参阅下面我在哪里使用$.each(errors.errors, //...来直接访问属性。以我的一些假设,您应该能够执行以下操作:

// mocking the data object for this example
var data = {responseJSON: {"message":"The given data was invalid.","errors":{"title":["The title field is required."],"slug":["The slug field is required."]}}};

var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';

$.each(errors.errors , function( key, value ) {
    errorsHtml += '<li><b>' + key + '</b> - ' + value[0] + '</li>';
});

errorsHtml += '</ul></div>';
$('#form-errors').html(errorsHtml);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="form-errors"></div>