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

93
Visualizações
Fetch value from server upon loading the window

I want it to load as soon as I open the window after fetching the data from the server side.

Here's the HTML:

    <body>
        <h1> Just another counter </h1>
        <div class="count-area">
            <button type="button" onClick="increment()"> + </button>
            <button type="button" onClick="decrement()"> - </button>
            <p>Count: <a id="clicks">0</a></p>
        </div>
    </body>
</html>

Here's the client side javascript:

window.onload = function() {
  fetch("/").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};

function increment() {
  fetch("/increment").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);

};

function decrement() {
  fetch("/decrement").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
  };

Once the increment decrement buttons are pressed then the correct count shows up, but until then it remains 0.

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

0

Instead of using windows.onload try using onload="myFunction()" on body :

function clicksLoad() {
  fetch("/").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};

function increment() {
  fetch("/increment").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);

};

function decrement() {
  fetch("/decrement").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
  };
<body onload="clicksLoad()">
  <h1>Just another counter</h1>
  <div class="count-area">
    <button type="button" onClick="increment()">+</button>
    <button type="button" onClick="decrement()">-</button>
    <p>Count: <a id="clicks"></a></p>
  </div>
</body>

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