I know this has been asked before, but my case is specific. I am not able to access JSON objects in my code, and I don't know why.
On a website I'm developing, I have an area with user comments. The page loads, and the comment area is populated with a JSON response from the server.
Here's my code:
// 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);
}
}
Here's the JSON response structure:
{
"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 console is showing me this message:
TypeError: comentarios is undefined[Learn More] codigo.js:447:19
But Firefox seems to have read JSON response:
What am I doing wrong? How can I access a JSON object and it's fields? I already researched the internet how can I do this, but I don't know what I'm doing wrong.