我认为这是一个非常基本的问题,但我花了数小时来寻找答案,却毫无运气,我有以下json 对象(通过游戏产生! Framework)
{
"preg.pregunta": [{
"message":"Debes escribir una pregunta",
"key":"preg.pregunta",
"variables":[]
}],
"preg":[{
"message": "validation.object",
"key":"preg",
"variables":[]
}]
}
这是我的密码
$.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.
}
});
我要全部进入 pregunta
( messessage
和 keey
值)
有帮助吗?
“强势”UPDed 强”:我没有足够的名声来回答我自己,这是我迄今发现的东西。
Ok Ok 说不定会更明显, 或者我还要多研究一点; 我发现jQuery没有正确分析JSON的反应,
有人知道为什么会这样吗?
我刚在 success
handler 中测试了这个代码, 并且运行良好!
$.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
}
});
更新二号
在搜索了大约两个小时后, 我找到了一个直接的解决办法:
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 返回一个描述错误的复杂对象, 响应Text 包含从服务器上检索的数据, 所以, 您必须使用 剖析JSON 函数来分析它 。
希望这有帮助!