请有人给我正确的代码来使用循环通过这个api



我正在尝试从天气api检索信息,以便我可以获得信息并显示它像一个7天的天气报告:

day: 1

云盖:1

风速:2

day: 2

云盖:3

风、速度:6

等。到目前为止,我有这个,它不工作,我不知道使用什么代码,甚至只是获取cloudcover的值。

weatherApi( "http://www.7timer.info/bin/api.pl?lon=31.049999&lat=-29.883333&product=astro&output=json&unit=metric");

async function weatherApi(file) {
let x = await fetch(file);
let y = await x.text();

const parsedJson = JSON.parse(y);



let text = "";
for (let i in parsedJson.dataseries.cloudcover) {
text += parsedJson.dataseries.cloudcover[i] + ", ";
}
document.getElementById("demo").innerHTML = text;


}

一些入门代码

天气API返回json数据,如下面的示例所示。"dataseries"是每天的天气指标数组。因此,您可以使用fetch方法来检索数据并自动将json转换为对象。一旦有了对象,就可以循环遍历数据系列数组,以便每天显示。显示数据的一种方法是使用模板字面量,然后可以将其附加到页面上。

{
"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"
}, 
...
<<p>

演示片段/strong>阅读链接的引用并运行代码片段,以更好地理解它是如何工作的。

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>";

最新更新