2016-04-26 7 views
1

これはajax呼び出しのエラーコールバック関数です。オブジェクトからの応答メッセージを出力しようとしています

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

私はコンソールにこれを送りますことから:

この戻っている
console.log(responseObj.message); 

var responseMsg = responseObj.message; 
if(typeof responseMsg =='object') { 
    var respObj = JSON.stringify(responseMsg); 
    console.log(respObj); 
} 
:私はこのような応答を文字列化した場合

Object {Invalid or missing parameters: Object} 
    Invalid or missing parameters: Object 
     email_already_in_use: "'Email' already in use" 

私はこれを得ます:

{"Invalid or missing parameters":{"email_already_in_use":"'Email' already in use"}} 

電子メールがすでに使用中であることをユーザーに印刷するにはどうすればよいですか?

完全なコールバック関数:あなたがメッセージの種類(「無効なまたは不足しているパラメータ」だけではなく)を持っている場合は、反復すべき

var errorMessages = responseObj.message["Invalid or missing parameters"]; 

for (var key in errorMessages) { 
    if(errorMessages.hasOwnProperty(key)){ 
    console.log(errorMessages[key]); 
    } 
} 

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

関連する問題