gpt4 book ai didi

javascript - 格式化 jqXHR 响应文本时出现错误消息

转载 作者:行者123 更新时间:2023-12-03 00:56:56 25 4
gpt4 key购买 nike

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

这可能吗?

最佳答案

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

关于javascript - 格式化 jqXHR 响应文本时出现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52787299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com