我认为这是一个非常基本的问题,但我花了几个小时寻找没有运气的答案,我有以下json对象(使用play生成!框架)
{ "preg.pregunta": [{ "message":"Debes escribir una pregunta","key":"preg.pregunta","variables":[] }],"preg":[{ "message": "validation.object","key":"preg","variables":[] }] }
这是我的jquery代码段
$.ajax({ type: $target.attr('method'),data: dataString,url:$target.attr('action'),dataType: "json",beforeSend: function() { //some stuff },success:function(response){ //some stuff },error: function(response){ //I want to use the json response here. } });
我想把所有内容都放在preg.pregunta(消息和键值)中
有帮助吗?
更新:我没有足够的声誉回答自己,这是我迄今为止所发现的.
好吧也许这将是显而易见的,或者我必须多学习一点;我发现jQuery没有正确解析JSON响应,如果它出现HTTP错误(在这种情况下为400).
有人知道为什么这种行为?
我刚刚在成功处理程序中测试了这段代码并且完美运行
$.ajax({ type: $target.attr('method'),beforeSend: function() { },success:function(response){ //It is working perfectly! $.each(response,function(object){ //first loop of the object $.each(response[object],function(values){ //looping inside arrays console.log(response[object][values].key) //getting value "key" console.log(response[object][values].message) //getting value "message" }); }) },error: function(response){ //nothing happens here } });
更新2.
搜索了大约2个小时后,我找到了一个简单的解决方案:
error: function(response){ //Note the jQuery.parseJSON function var response = jQuery.parseJSON(response.responseText); $.each(response,function(object){ $.each(response[object],function(values){ console.log(response[object][values].key) console.log(response[object][values].message) }); }) }
说明:使用错误处理程序时,jQuery返回描述错误的复杂对象,responseText包含从服务器检索的数据,因此,您必须使用parseJSON函数对其进行解析.
希望这可以帮助!
解决方法
试试这个:
error: function(response) { var pregunta = response["preg.pregunta"][0].message; var key = response["preg.pregunta"][0].key; },
如果preg.pregunta数组中有多个值,则需要循环并用迭代变量替换[0].
另外,我不太明白你为什么只想在错误处理程序中访问响应?
最后,访问JSON的代码是本机javascript.这是因为当您收到响应时它已转换为POJS对象,不需要jQuery.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。