简体   繁体   中英

How to automatically update weather data (JSON) on a website using JavaScript?

Hi I'm trying to create a website that shows you current weather(in 3 cities for now). My problem is that I don't know how I can get only the JSON data to update when the switch is in the ON position. (So I don't want to reload the page after the interval I just want to automatically update the temperature etc. after a certain timeperiod.)

Here is a picture of the website: 在此处输入图片说明

Here is my implementation. Can't seem to figure this out since in my opinion this should work :D Been staring at this for way too long now.

JavaScript

function setup() {
  var dropinput = document.getElementById("city-dropdown");
  var value = dropinput.options[dropinput.selectedIndex].value;
  var url = api + value + units + apiKey;
  fetch(url).then(
    function(response) {
    if (response.status !== 200) {
      console.log('Looks like there was a problem. Status Code: ' +
      response.status);
      return;
    }
    response.json().then(function(data) {
      document.getElementById("temp").innerHTML = 'Temperature: ' + data.main.temp + ' Celsius'
      document.getElementById("wind").innerHTML = 'Wind: ' + data.wind.speed + ' m/s'
      document.getElementById("humidity").innerHTML = 'Humidity: ' + data.main.humidity + '%'
    });
    }
  )

}

var interval = null;

function autoupdate() {
  var checkBox = document.getElementById("switch");
  if (checkBox.checked == true) {
    interval = setInterval(setup(), 1000);
  } else {
    clearInterval(interval);
  }
}

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="slideshow.js"></script>
</head>
<body onload="setup()">
<div class="container">

  <h1>Check the weather!</h1>
  <fieldset>
    <form action="/" method="post">
      <select name="city" id="city-dropdown">
          <option value="Helsinki">Helsinki</option>
          <option value="Turku">Turku</option>
          <option value="Kuusamo">Kuusamo</option>
      </select>
      <button class="nappi" type="button" onclick="setup()">Get weather</button>
    </form>
  </fieldset>
  <p id="temp">Temperature: </p>
  <p id="wind">Wind: </p>
  <p id="humidity">Humidity: </p>

</div>

<div class="update">
    <p id="autoupdate">Auto-update:</p>
    <label class="switch">
      <input type="checkbox" id="switch" onclick="autoupdate()">
      <span class="slider round"></span>
    </label>
  </div>
  </body>
  </html>

您需要这样做:

setInterval(function(){setup()}, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM