2016-04-26 41 views
1

这是我从ajax调用中的错误回调函数。尝试打印出对象的响应消息

error: function(xhr, status, error) { 
    var responseObj = jQuery.parseJSON(xhr.responseText); 
} 

从那个我送这个控制台:如果我字符串化这样的反应

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

console.log(responseObj.message); 

这是恢复该

我得到这个:

{"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); 
} 

回答

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]); 
     } 
    } 
    } 
} 
+0

工作,谢谢 – Jason