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

274
Visualizações
How to get xhr data in javascript

I'm a newbie at javascript and I made this script which runs on page load:

function checkItem(itemToCheck) {
  console.log(`Checking if ${itemToCheck} is checked`)
  var url = `https://list.s40.repl.co/api/get-status/${itemToCheck}`;

  var xhr = new XMLHttpRequest();
  xhr.open("GET", url);

  xhr.setRequestHeader("Accept", "application/json");

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        console.log(xhr.status);
        console.log(xhr.responseText);
    }};

  xhr.send();
  if (status === 200) {
    console.log("The request worked")
    if (response == `True`) {
      console.log(`${itemToCheck} is true`)
      var checkbox = document.getElementById(`${itemToToggle}-checkbox`)
      //Control the checkbox
    }
  }
}

It never outputs the "The request worked" text, and it seems to be because the xhr.status and xhr.responseText are blank outside of that function they're in. I know nothing about javascript and I don't know how to fix this. All I want to do is be able to request data and then do something with it if it equals true. Please help

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I get xhr.status == 0, which means the request failed. When I run the request through postman, I get an SSL error (certificate has expired). That is probably why the request fails.

Running it with fetch is not a problem though. So fetch seems to skip the SSL error. There doesn't seem to be a way to make XMLHttpRequest ignore this SSL error, though.

fetch(`https://list.s40.repl.co/api/get-status/2`)
  .then(res => res.text())
  .then(console.log)

I advise you to check if you can just use fetch for the task. Only very old browsers don't support it: https://caniuse.com/fetch

It is higher level and async by nature. You should generally prefer async code over synchronous when writing for the browser, as synchronous code blocks execution quickly and slows down your browser application or makes it even freeze.

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