简体   繁体   中英

Unable to retrieve Json error messages from response in Ajax error handler

I have an ajax request that has an error handler that outputs the errormessages returned in a json response like this: (Ignore the second for loop I'm just showing what I tried already, the part that should have worked afaik was the alert(error) or alert(error.msg) in the first for loop):

error: function(xhr){
                    var error_array = $.parseJSON(xhr.responseText);
                    for (var error in error_array){
                        for (var err in error){                        
                            alert(err);
                        }   
                        //alert(error['msg'];
                        //alert(error.msg);
                        //alert(error);
                    }

                }

The json that is being returned by my controller is structured like this: 在此处输入图片说明

The only values so far I have been able to get out of this response are 0 and 1 when using alert(error) and undefined when I do anything else, can anyone help me with getting these error messages from the response in my javascript function?

EDIT: if I do alert(error_array) I get my 2 strings separated by a comma

You're alerting object key, not a value. To get a value you should:

alert(error[err]);

The comment and answer posted weren't exactly what I was looking for but pushed me into the right direction to find the proper way to get my error messages, this is how I got it to work:

error: function(xhr){
                var error_array = $.parseJSON(xhr.responseText);
                for (error in error_array){
                    alert(error_array[error].msg);
                }

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM