2
I’m taking information from the database and putting it into an array: (more details of the code)
var alunos = {};
var self = 0;
function sortearAluno(){
var dataForm = {'tipo': "listar"};
$.ajax({
type:'post',
data: dataForm,
dataType: 'json',
url: 'alunoDAO.php',
success: function(dados){
var alunos = {};
for(var i=0;dados.length>i;i++){
self++;
alunos['a'+self] = {
idAluno : dados[i].idAluno,
nome: dados[i].nome,
classe : dados[i].classe,
hp : dados[i].hp,
ap : dados[i].ap,
xp : dados[i].xp,
};
}
}
});
}
So far it’s normal, when I run the code it can create.
Console in Chrome:
But then, when I try to get the Keys' values, I can’t. I’ve tried several ways, I’ve searched every page that google showed me, but I can’t find anything that works.
Some of my attempts:
console.log(alunos.a1)
Displays = "Undefined"
console.log(alunos[a1].nome)
Displays = "Uncaught Referenceerror: a1 is not defined"
Among other things I’ve tried. So, does anyone know how to solve this or has some better way to do it?
What appears with
console(alunos['a1'].nome)
?– Victor Stafusa
Are you creating this object inside the ajax callback and using it outside of it? You can show more code and an example of the content of
dados
?– Sergio
@Victorstafusa For your information, index an object with
.
is the same as indexing an object computed with[...]
, the difference is that with the.
you can only declare a valid Ecmascript identifier, so the same as indexing an object with aString
. That is, there will be almost the same mistake if you try to make an expression likealunos['a1'].nome
instead ofalunos[a1].nome
, the error will be different because you are declaring a String in indexing, for example:Uncaught TypeError: Cannot read property 'nome' of undefined
– Klaider
Victor, aparece " Uncaught Typeerror: Cannot read Property 'nomeP' of Undefined".
– DanielFelipe01
Sergio, update the post with more parts of the code
– DanielFelipe01
And people tried to do what Victor said inside the ajax callback as Sergio commented and it worked. I figured because I declared the students out of office and added the data and then using that same variable would work, but it doesn’t look like it. Thank you!
– DanielFelipe01