我知道以前曾经问过,但我的情况是具体的。我无法在代码中访问JSON对象,我也不知道原因。
在我正在开发的网站上,我有一个有用户评论的区域。页面加载,注释区域填充来自服务器的JSON响应。
这是我的代码:
// Offset = 0
// Limite = 10
// This is a request.
var pedidoComentarios = new PedidoComentarios(0 , 10);
// Get the last comments.
function getUltimosComentarios()
{
return $.ajax({
"url": "ultimos-comentarios-ajax",
"type": "POST",
"dataType": "json",
"contentType": "application/json; charset=utf-8",
"async" : true,
"cache" : false,
"processData" : false,
"data": JSON.stringify(pedidoComentarios),
"success": function(data)
{
alert("Sucesso: " + data);
alert("Conteúdo: \n\n" + JSON.stringify(data));
// This will increment the offset.
pedidoComentarios.offset += pedidoComentarios.limite;
return data;
},
"error": function(xhr , status , error)
{
if (xhr.status === 0)
{
alert('Not connect.\n Verify Network.');
}
else if (xhr.status == 404)
{
alert('Requested page not found. [404]');
}
else if (xhr.status == 500)
{
alert('Internal Server Error [500].');
}
else if (error === 'parsererror')
{
var tipoResposta = xhr.getResponseHeader("content-type");
if(tipoResposta.indexOf('html') > -1)
{
window.location.reload();
}
else
{
alert('Requested JSON parse failed.');
}
}
else if (error === 'timeout')
{
alert('Time out error.');
}
else if (error === 'abort')
{
alert('Ajax request aborted.');
}
else
{
alert('Uncaught Error.\n' + xhr.responseText);
}
}
});
}
// When the right area is selected, the comments are loaded from the server.
if($('#area-comentarios').length != 0)
{
alert('Enviando pedido de comentários...');
var resposta = getUltimosComentarios();
var comentarios = resposta.comentarios;
// This line (447) of code is throwing a error.
for(var c = 0 ; c < comentarios.length ; c++)
{
addComentario(
$('#area-comentarios #comentarios') ,
comentarios[c].autor + " - " + comentarios[c].dataHora ,
comentarios[c].conteudo);
}
}
这里是JSON响应结构:
{
"comentarios" : [ {
"autor" : "Person 001",
"conteudo" : "Content 001",
"dataHora" : "10/03/2017 - 15:27:35"
}, {
"autor" : "Person 002",
"conteudo" : "Content 002",
"dataHora" : "10/03/2017 - 14:28:26"
}, {
"autor" : "Person 003",
"conteudo" : "Content 003",
"dataHora" : "10/03/2017 - 14:24:23"
} ]
}
Firefox控制台正在向我显示此消息:
TypeError:comentarios未定义[了解更多] codigo.js:447:19
但Firefox似乎已经阅读了JSON响应:
我做错了什么?如何访问JSON对象及其字段?我已经researched互联网如何做到这一点,但我不知道自己做错了什么。