错误消息格式化jqXHR响应文本

时间:2018-10-12 21:37:35

标签: javascript jquery ajax

我是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 :(得分:1)

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);