javascript - 格式化 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
这可能吗?
解决方案
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);
推荐阅读
- python - 如何在 DJANGO_SETTINGS_MODULE 中定义环境变量?
- java - Document Root-Element "beans" 必须匹配 DOCTYPE-Root "xml"
- python - 带有字符的 Python 列表/集合理解
- html - 旋转中间 flex 列效果
- android - 搜索视图或带有子菜单的对话框?
- python - MySQLdb/_mysql.c(29):致命错误 C1083:无法打开包含文件:'mysql.h':没有这样的文件或目录
- java - Hibernate:如何在争用/高并发下推理 Optimistic Locking Exception?
- c - 寄存器变量导致执行时间不同,为什么?
- .net-core - 如何读取要在 Azure WebApp for Linux 上部署的 .net core 2.1 mvc 应用程序的 appsettings.json
- google-apps-script - 谷歌应用程序脚本,如何创建一个在更改工作表名称时激活的事件对象脚本?