我有一个Ajax请求,返回一个json哈希,如果出现错误,则包括错误信息。以下是一个示例:
为什么使用该方法可以将文本正确地插入到DOM中,而使用Dampsquid或其他任何方法都只会返回空字符串,这让我想不通。
{"success":false,"errors":{"image":["file must be at least 1024x768px in size."]},"content_type":"text/json"}
基于这个问题,我能够找出如何打印哈希表的一部分:
JSON.stringify( responseJSON.errors )
然而,这仍然以代码哈希值的形式打印出来,例如:{"image":["file must be at least 1024x768px in size."]}
我真的很想将其简化为:
Image file must be at least 1024x768px in size.
除了在 stringify
之后使用 .replace
,还有没有直接的方法来做到这一点?请注意,错误哈希可能包含更多的错误,例如:
{"image":["file must be at least 1024x768px in size."],"file":["type is invalid, must be jpg, png, or gif"]}
更新:我不知道为什么,但下面显示的所有函数都不能在传递responseJSON
对象时返回字符串。然而,使用jQuery直接将内容添加到DOM中是有效的。这是我最终采用的方法:
// In the middle of an ajax callback
$('.qq-upload-failed-text:last').append(': <span class="explanation"></span>');
formatErrors( responseJSON );
// As a stand-alone function so it can be reused
function formatErrors( response ) {
$.each( response.errors, function(key, value) {
$('span.explanation:last').append( key + " " + value );
});
}
为什么使用该方法可以将文本正确地插入到DOM中,而使用Dampsquid或其他任何方法都只会返回空字符串,这让我想不通。