以下是来自ajax调用的错误回调函数。
error: function(xhr, status, error) {
var responseObj = jQuery.parseJSON( xhr.responseText );
}
我将其发送到控制台:
console.log(responseObj.message);
返回此内容:
Object {Invalid or missing parameters: Object}
Invalid or missing parameters: Object
email_already_in_use: "'Email' already in use"
如果我将响应字符串化为:
var responseMsg = responseObj.message;
if(typeof responseMsg =='object') {
var respObj = JSON.stringify(responseMsg);
console.log(respObj);
}
我明白了:
{"Invalid or missing parameters":{"email_already_in_use":"'Email' already in use"}}
如何向用户打印他们的电子邮件已被使用?
完整的回调函数:
error: function(xhr, status, error) {
var responseObj = jQuery.parseJSON( xhr.responseText );
var responseMsg = responseObj.message;
if(typeof responseMsg =='object') {
var respObj = JSON.stringify(responseMsg);
console.log(respObj);
} else {
if(responseMsg ===false) {
console.log('response false');
} else {
console.log('response something else');
}
}
console.log(responseObj.message);
}
答案 0 :(得分:3)
你可以这样做:
var errorMessages = responseObj.message["Invalid or missing parameters"];
for (var key in errorMessages) {
if(errorMessages.hasOwnProperty(key)){
console.log(errorMessages[key]);
}
}
如果您有不同类型的消息(不仅是“参数无效或缺失”),您应该首先迭代消息数组:
var errorMessages = responseObj.message;
for (var errorType in errorMessages){
if(errorMessages.hasOwnProperty(errorType)){
console.log(errorType + ":");
var specificErrorMsgs = errorMessages[errorType];
for (var message in specificErrorMsgs) {
if(specificErrorMsgs.hasOwnProperty(message)){
console.log(specificErrorMsgs[message]);
}
}
}
}