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

149
Visualizações
Javascript is not accepting JSON data as variable

I am trying to connect to an API to display some data on my website.

I've already defined Http as new XMLHttpRequest();, and url as the API endpoint.

Here's the code:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
      var api = JSON.stringify(Http.responseText)
      document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}

However, when I run the code, I get the following error:

Uncaught TypeError: api.total_bandwidth is undefined

What is wrong here? Is Http.responseText already an Object? Did I define the API wrong?

This is the response of api:

{"total_bandwidth": {"GB": 110842.05, "TB": 108.24, "PB": 0.11}}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're stringifying the object (response), then trying to get "TB" from a string.

Try parsing api then getting the properties from it:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
    var api = JSON.stringify(Http.responseText);
    var apiJson = JSON.parse(api);
    document.getElementById("stat").innerHTML = "Powering over " + apiJson.total_bandwidth.TB + "TB of private internet traffic";
};

Edit: Turns out that "JSON.stringify" was actually a mistake.

I think you meant to use JSON.parse rather than JSON.stringify... - Robin Zigmond

I think you meant JSON.parse (to PARSE the response text) instead of JSON.stringify:

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
      var api = JSON.parse(Http.responseText);
      document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}

Learn more about JSON.parse at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

about 4 years ago · Juan Pablo Isaza 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