首页 > 解决方案 > 格式化 jqXHR 响应文本的错误消息

问题描述

我是 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

这可能吗?

标签: javascriptjqueryajax

解决方案


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


推荐阅读