我认为这是一个非常基本的问题,但我花了好几个小时寻找答案,没有运气,我有下面的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.pregunta
(message
和key
值)
有什么帮助吗?
已更新:好吧,我没有足够的声望回答自己,这是我迄今为止发现的。
好吧,也许它会更明显,或者我有更多的研究;我发现,如果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函数解析它。
希望这会有所帮助!
嗨!我已经尝试过,但没有成功,“响应['preg.pregunta']未定义” –
当您尝试以下操作时,您在控制台中看到了什么:'console.log(response);'? –
Hi Rory,我的回答很简单;我正在使用playframework验证器验证字段,如果发现任何错误(例如字段为空),则会返回一个呈现为JSON的validation.errorsMap()对象,以便稍后使用它,此响应将返回“HTTP 400' ...所以这就是为什么我用'error'处理程序来捕获它。 –