一些帮助您入门的代码
天气 API 返回 json 数据,如下面的示例所示。 “dataseries”是每天的天气指标数组。因此,您可以使用fetch method 检索数据并自动将 json 转换为对象。一旦你有了对象,你就可以loop通过dataseries数组来显示每一天。显示数据的一种方法是使用template literals,然后您可以将其附加到页面。
{
"product": "astro",
"init": "2022060912",
"dataseries": [{
"timepoint": 3,
"cloudcover": 1,
"seeing": 6,
"transparency": 3,
"lifted_index": 2,
"rh2m": 9,
"wind10m": {
"direction": "S",
"speed": 4
},
"temp2m": 22,
"prec_type": "none"
},
...
演示片段
阅读链接的参考并运行代码 sn-p 以更好地了解其工作原理。
function getWeather(longitude, latitude, title) {
const url = `https://www.7timer.info/bin/astro.php?lon=${longitude}&lat=${latitude}&ac=0&unit=metric&output=json&tzshift=0`;
fetch(url)
.then(response => response.json())
.then(data => {
let html = `<h3>Weather for ${title}</h3>`;
data.dataseries.forEach((item, index) => {
html += (`
<div class="day">
<strong>Day ${1 + index}</strong>
<div>Cloud Cover: ${item.cloudcover}</div>
<div>Wind Direction: ${item.wind10m.direction}</div>
<div>Wind Speed: ${item.wind10m.speed}</div>
<div>Temp: ${item.temp2m}</div>
</div>
`);
});
weather.innerHTML = html;
});
}
// lat -29.9 lat, long 31, Durban, South Africa
getWeather(31, -29.9, "Durban, South Africa");
body {
font-family: sans-serif;
background-color: whitesmoke;
}
.day {
margin: 1em;
padding: 0.25em;
border: 1px solid steelblue;
background-color: white;
}
<div id="weather"></div>
更新
在评论中,OP 询问如何在不使用模板文字的情况下构建显示:
html += "<div class='day'>" +
"<strong>Day " + (1 + index) + "</strong>" +
"<div>Cloud Cover: " + item.cloudcover + "</div>" +
"<div>Wind Direction: " + item.wind10m.direction + "</div>" +
"<div>Wind Speed: " + item.wind10m.speed + "</div>" +
"<div>Temp: " + item.temp2m + "</div>" +
"</div>";