2012-05-26 58 views
6

我认为这是一个非常基本的问题,但我花了好几个小时寻找答案,没有运气,我有下面的json对象(使用play!Framework生成)如何使用jquery解析json对象

{ 
    "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.preguntamessagekey值)

有什么帮助吗?

已更新:好吧,我没有足够的声望回答自己,这是我迄今为止发现的。

好吧,也许它会更明显,或者我有更多的研究;我发现,如果jQuery响应HTTP错误(本例中为400),jQuery不会正确解析JSON响应。

有人知道为什么会有这种行为?

我刚刚在success处理程序中测试了这段代码,并且完美地工作!

$.ajax({ 
    type: $target.attr('method'), 
    data: dataString, 
    url:$target.attr('action'), 
    dataType: "json", 
    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函数解析它。

希望这会有所帮助!

回答

2

试试这个:

error: function(response) { 
    var pregunta = response["preg.pregunta"][0].message; 
    var key = response["preg.pregunta"][0].key; 
}, 

如果有在preg.pregunta阵列内的多个值,你就需要循环,并与你的迭代变量替换[0]

此外,我不明白为什么你只想访问error处理程序中的响应?

最后,访问JSON的代码是原生javascript。这是因为当您收到响应时,它已被转换为POJS对象,不需要jQuery。

+0

嗨!我已经尝试过,但没有成功,“响应['preg.pregunta']未定义” –

+0

当您尝试以下操作时,您在控制台中看到了什么:'console.log(response);'? –

+0

Hi Rory,我的回答很简单;我正在使用playframework验证器验证字段,如果发现任何错误(例如字段为空),则会返回一个呈现为JSON的validation.errorsMap()对象,以便稍后使用它,此响应将返回“HTTP 400' ...所以这就是为什么我用'error'处理程序来捕获它。 –