我有以下 JSON 字符串从 PHP 5.3.10 的 json_encode 函数返回到 jQuery 1.9.1
{
"messsages":{
"error":["API_CONTROLLER.INVALID_LOGIN_PASSWORD"],
"warning":[],
"notice":[],
"success":[]
},
"result":false
}
jQuery 代码:
$.ajax(targetURL, {
type: method,
data: params,
dataType: "json",
success: function(resp){
console.log(resp); //Shows object with all vars correctly displayed
//The for loop also outputs all keys and values correctly
for(var i in resp){
console.log("I: "+i);
console.log("RESP: ");
console.log(resp[i]);
}
console.log("DIRECT ACCESS");
console.log(resp.messages); //WHY undefined?
//console.log(resp.messages[error]); //undefined
//console.log(resp.messages[error][0]); //undefined
//console.log(resp.messages.error); //undefined
//console.log(resp.messages.length); //Just trying => undefined
console.log(resp.result); //this works!
//console.log(resp[messages]); //Just trying => undefined
}
});
如何访问消息?
第一个 console.log 和循环显示消息存在,并且 messages.error、messages.notice 等存在。但我怎样才能访问它们呢?这是一种 jQuery 错误吗?
最佳答案
您的回复的消息变量名称中有三个“s”。因此它在循环中有效,但当您尝试访问不存在的“消息”时会失败。
关于javascript - 无法直接访问 ajax 响应属性,尽管它存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15655747/