Обработка ошибок в Ajax возвращает неопределенное значение - PullRequest
0 голосов
/ 21 февраля 2019

Я пытаюсь показать ошибки, когда Ajax не удается, но я не могу углубиться в результаты, чтобы показать точную ошибку.

sample

вот что я получаю на вкладке сети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 и value из errors part.

Issue

На основании приведенного выше кода, если я повторяю цикл 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>';
});

, это не работает.

Вопрос

Как я могу получить мои ошибки часть и вернуть эти key & value?

1 Ответ

0 голосов
/ 21 февраля 2019

Переменная 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...