【发布时间】:2021-03-05 02:25:21
【问题描述】:
我正在使用 openweathermap.org API,并且正在使用 javascript 来获取数据,然后发布到 HTML。我有两个 javascript 函数。获取当前天气的一个功能非常有效 - 第二个功能是拉 5 天预报。我已经到了可以提取数据的地步,但是我需要遍历该数据并发布到 HTML。函数如下:
function getForecast() {
let forecast_icon = document.getElementById("forecast_icon");
let forecast_temperature = document.getElementById("forecast_temperature");
let api = "https://api.openweathermap.org/data/2.5/weather";
let apiKey = "API KEY";
location.innerHTML = "Locating...";
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
let url = api + "?lat=" + latitude + "&lon=" + longitude + "&appid=" + apiKey + "&units=imperial";
fetch(url)
.then(response => response.json())
.then(forecast => {
console.log(forecast);
let temp = forecast.main.temp;
forecast_temperature.innerHTML = Math.round(temp) + "°F";
let icon = forecast.weather[0].icon;
forecast_icon.innerHTML = '<img src="http://openweathermap.org/img/wn/' + icon + ".png" + '"/>';
});
}
function error() {
location.innerHTML = "Unable to retrieve your location";
}
}
getForecast();
这是 HTML - 非常简单:
<ul>
<li>
<div id='forecast_icon'></div>
<div class='temperature-sensor-day' id='forecast_temperature'></div>
</li>
</ul>
我不确定如何遍历数据并将每个结果发布到 HTML。我会继续搜索,但希望得到一些指导。
编辑:
我需要遍历 API 调用的输出并将该数据发布到上面显示的 HTML 中。
我尝试使用“承诺”。我在搜索中看到了这个:
for (url in urls){
time = getData(urls[url])
console.log(time)
ttTimes.push(time)
};
我尝试替换我的值,但由于这个使用了两个 url,我无法弄清楚如何让它工作。
我还看到了不同类型的循环,所以我对最好的方法感到困惑。
下面是它的外观图片。您可以看到五天中只有一天在填充。希望这有助于可视化问题。
【问题讨论】:
-
您没有从 API 调用中提供样本数据,这使得您很难猜测您需要帮助循环的数据结构。
-
您没有显示任何尝试单步执行数据的尝试,并且可能尝试对其进行编辑。您的代码调用了 api。我正在使用手机,但一个好的开始是查看地图,对于 dontenv,我在遇到问题时发布了一个关于它的问题:stackoverflow.com/questions/57213162/…
-
最好把它贴进去并解释一下,因为现在它完全不见了。
-
我在这里删除和/或编辑了一堆 cmets 以删除对投票的讨论。 请不要在 cmets 中讨论投票。投票是匿名的,没有人会给出投票的理由,无论是赞成还是反对。
-
坦率地说,史蒂夫,关于你可以在哪里与我聊天的问题的答案是“无处”。这不是真正值得辩论或讨论的事情。这只是网站政策。你说“无缘无故投票”,但事实并非如此。反对者有一个理由。他们只是选择不发表评论。那是另一回事。原因在向下投票箭头的工具提示中给出。我同意,建设性的批评是受欢迎的,但它是可选的。抨击反对者是不受欢迎的。另见:the relevant FAQ on Meta
标签: javascript json function loops openweathermap