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

214
Visualizações
javascript url call executing twice

I am trying to show this json data in a javascript alert box, but it shows it twice (same content). It is working, but I do not know why it is displaying two alerts. (javascript is not my preferred language).

This is the response from the URL called:

{
  "type": "error",
  "response": {
    "message": "Could not start app"
  }
}

This is the code I am using:

<script type="text/javascript">
       
        function call() {
            const Http = new XMLHttpRequest();
            const url='https://url_to_get_the_response';
            Http.open("GET", url);
            Http.send();
            Http.onreadystatechange = (e) => {
                if (Http.responseText) {
                alert(Http.responseText);
               }
           }
    }
    </script>

And I get two alerts, both containing the same thing (the .json result). I only want one of them.

I have tried adding a return; and break call; in the if (Http.responseText) section. Adding the return; in the if statement didn't do anything and adding the break call; stopped it working.

Any advice on this? Thanks.

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

0

You approach is correct. onreadystatechange event is triggered multiple times, as the readyState attribute changes from the beginning to the end of an API call.

On adding if condition for the appropriate readyState and status value that comes in the XMLHttpRequest Object. Solves this issue.

You can read more about those attributes here readyState, status

function call() {
        const Http = new XMLHttpRequest();
        const url='https://jsonplaceholder.typicode.com/todos/1';
        Http.open("GET", url);
        Http.send();
        Http.onreadystatechange = (e) => {
            if (Http.readyState == 4 && Http.status == 200 && Http.responseText) {
            alert(Http.responseText);
           }
       }
  }
<button onclick='call()'>Call</button>

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