Сообщение об ошибке форматирования текста ответа jqXHR - PullRequest
0 голосов
/ 13 октября 2018

Я довольно новичок в AJAX / Jquery и создал ответ об ошибке в моей программе, но у меня проблема с тем, как появляются ошибки, в основном с jqXHR.responseText.

error: function(jqXHR, textStatus, errorThrown) {
         $('.result').show().html('<p><strong>' 
          + textStatus +'</strong></p><div>'+ jqXHR.responseText +' </div>');
}

Это показываеткак

error 
{"comment":["The comment field is required."]}

Как бы я убрал "" и скобки из jqXHR.responseText, чтобы он выглядел как

error 
Comment: The comment field is required

Возможно ли это?

1 Ответ

0 голосов
/ 13 октября 2018

var responseText = '{"comment":["The comment field is required."]}'
//desired result = Comment: The comment field is required.
var responseTextAsAnObject = JSON.parse(responseText);
var errorKey = Object.keys(responseTextAsAnObject)[0];
//errorKey should be "comment"
console.log(errorKey);
var firstErrorMessage = responseTextAsAnObject[errorKey][0];
//firstErrorMessage should be "The comment field is required."
console.log(firstErrorMessage);
//We need to capitalize the errorKey
errorKey = errorKey[0].toUpperCase() + errorKey.slice(1);
console.log(errorKey);
//Now we can construct our desired result
var result = errorKey +': '+ firstErrorMessage;
console.log(result);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...