JSON数据闪烁在刷新上,功能以避免每次绘制新数据



我正在尝试使用Moment.js和OpenWeatherapi制作一个小应用程序。为了更新时间,我正在尝试重新加载页面" x"的每一个时间。每当发生这种情况时,我的JSON数据都会闪烁..我以前看过几个问题,但仍在挣扎。

我正在使用

setTimeout(function(){
   window.location.reload(1);
}, 5000);

这是我的代码的样子:

 <div id = "data"></div>
   <ul class = "weatherData">
    <li id = "city"></li>
    <li id = "weatherType"></li>
    <li id = "fTemp"></li>
    <li id = "windSpeed"></li>
  </ul>
</div>

<script>
$(document).ready(function(){

  var api = 'http://api.openweathermap.org/data/2.5/weather?
lat=39.729431&lon=-104.831917&appid=97f35dee6354ab9d2bac7c56a4c4a6fe';
  $.getJSON(api, function(data){
      var weatherType = data.weather[0].description; 
      var city = data.name;
      var windSpeed = data.wind.speed; 
      var kTemp = data.main.temp;
      var fTemp;
      var cTemp;
    fTemp = (kTemp*(9/5)-459.67).toFixed(2);
    cTemp = (kTemp-273).toFixed(2);
    windSpeed = (2.237*(windSpeed)).toFixed(1);

 $('#city').html(city);
 $('#weatherType').html(weatherType);
 $('#fTemp').html(fTemp + " &#8457;");
 $('#windSpeed').html(windSpeed + " mph ");
  });
});

</script>
<script> 
var time = moment().format("h:mm");
var NowMoment = moment().format('LL');
var day = moment().format('dddd');
var eDisplayMoment = document.getElementById('displayDate');
  eDisplayMoment.innerHTML = NowMoment;

var eDisplayTime = document.getElementById('displayTime');
    eDisplayTime.innerHTML = time; 
document.getElementById('displayDay').innerHTML = day;

</script>

有人可以指导我做什么?

您只需要将代码包装在称为getweather的函数中,然后从setInterval调用它。这将重新运行代码,而不是整个页面。

$(document).ready(function() {

  var api = 'http://api.openweathermap.org/data/2.5/weather?lat = 39.729431 & lon = -104.831917 & appid = 97 f35dee6354ab9d2bac7c56a4c4a6fe ';
  function getWeather() {
    $.getJSON(api, function(data) {
      var weatherType = data.weather[0].description;
      var city = data.name;
      var windSpeed = data.wind.speed;
      var kTemp = data.main.temp;
      var fTemp;
      var cTemp;
      fTemp = (kTemp * (9 / 5) - 459.67).toFixed(2);
      cTemp = (kTemp - 273).toFixed(2);
      windSpeed = (2.237 * (windSpeed)).toFixed(1);

      $('#city').html(city);
      $('#weatherType').html(weatherType);
      $('#fTemp').html(fTemp + " &#8457;");
      $('#windSpeed').html(windSpeed + " mph ");
    });
  };

  getWeather();
  setInterval(getWeather, 5000)
});

最新更新