刷新时JSON数据闪烁,每次都避免绘制新数据的功能......?

时间:2017-04-17 02:25:47

标签: javascript html 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>

有人可以指导我做什么吗?

1 个答案:

答案 0 :(得分:0)

您只需将代码包装在名为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)

});