javascript API调用导致旧数据

javascript API call results in old data

本文关键字:数据 API 调用 javascript      更新时间:2023-09-26

我有一个天气web api,我需要在网站上显示当前城市的天气报告。每当代码调用API时,它只会产生旧数据。数据永远不会改变,当我在浏览器上运行web API URL时,它的结果正是我想要的。请帮助我缓存数据的原因。

webAPI

http://api.openweathermap.org/data/2.5/weather?lat=26.894049&lon=80.942686&mode=json

我的代码

$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + 'mode=json&rand=' + Math.random(), function (data) {
    var wind = {};
    var temp = {};
    wind = data.wind;
    temp = data.weather;
    var clouds = '%' + data.clouds.all;
    var description = data.weather[0].description;
    var temp = data.main.temp - 273.15;
    var humidity = data.main.humidity + '%';
    var icon = data.weather[0].icon;
    weatherImg = "<img height='"45'" width='"45'" style='"border: medium none; width: 45px; height: 45px;position:relative;top:-10px; background: url('http://openweathermap.org/img/w/" + icon + ".png') repeat scroll 0% 0% transparent;'" alt='"title'" src='"http://openweathermap.org/images/transparent.png'">";
    document.getElementById('weatherImg').innerHTML = weatherImg;
    document.getElementById('current_temp').innerHTML = (temp) + '&deg;C';
    document.getElementById('current_wind').innerHTML = ' ; ' + wind.speed + 'Km/h';
    document.getElementById('city_name').innerHTML = data.name;
});

测试了您的代码在一段时间内运行良好,api响应很慢,但除此之外,对我来说一切都很好

htttp://jsfiddle.net/navneetccna/un2u5j0v

脚本前缀模式中的url不应该使用&。你应该把这个放在次要位置/说得更具体一些。你说你得到的是旧数据。您是否得到了一个根本不更改或很少更改的旧JSON响应?