Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
access value of JSON by key using ajax doesn't display result

I have a JSON data looking like this (it's not an object, it's an array):

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
  }
]

and a function to get data and display it using AJAX, I use JSON.parse() to get the JSON from string: Initialize a XMLHttpRequest object:

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
        var jsonObj = JSON.parse(xhttp.responseText);

Add a new element to the document:

var table='<tr><th>Name</th><th>Email</th></tr>';
        table += '<tr><td>' +
            jsonObj["name"] +
            '</td><td>' +
            jsonObj["email"] +
            '</td></tr>'
        document.getElementById('demo').innerHTML = table;
    }
};

But when I run the browser doesn't display value in the table field, it shows undefined. Is there something wrong? I also changed to use JSON.stringtify(), but the result still didn't change. Please help me to figure out the problem

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You should a loop to iterate the array like @Lee Taylor said.

for (var item of jsonObj) {
    table += "<td>" + item.name + "</td>"
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda