简体   繁体   English

无法从Ajax错误处理程序中的响应中检索Json错误消息

[英]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): 我有一个ajax请求,该请求具有一个错误处理程序,该错误处理程序输出在json响应中返回的错误消息,如下所示:(忽略第二个for循环,我只是显示我已经尝试过的内容,应该已经有效的部分是alert(error )或第一个for循环中的alert(error.msg):

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: 我的控制器返回的json的结构如下: 在此处输入图片说明

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? 到目前为止,我能够从此响应中获得的唯一值是在使用alert(error)时为0和1,在执行其他操作时未定义,有人可以帮助我从我的javascript函数中获取响应中的这些错误消息吗?

EDIT: if I do alert(error_array) I get my 2 strings separated by a comma 编辑:如果我做alert(error_array)我得到我的2个字符串用逗号分隔

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

            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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