← 第 5 关 – 发明家

第 2/8 课 ⏱ 30 分钟 高级版

你的第一次 fetch

用 JavaScript 直接调用 API,把响应显示在页面上。

跟我看:fetch——用代码下单

上一课你手动在浏览器打开 API。现在 JavaScript 做同样的事——用 fetch 命令:

const adresa = 'https://api.open-meteo.com/v1/forecast?latitude=49.19&longitude=16.61&current_weather=true';

const odpoved = await fetch(adresa);
const data = await odpoved.json();

console.log(data.current_weather.temperature);

逐行发生了什么:

  1. fetch(adresa)——发请求(服务员去厨房)。
  2. await—— 它回来。互联网要一点时间!
  3. odpoved.json()——把响应变成 JavaScript 对象。
  4. 然后像普通对象一样用:点点,搞定。
⚠️

await 只能在标了 async 的函数里,或在 <script type="module"> 里。浏览器报 “await is only valid in async functions” 时,这样包起来:

async function nacti() {
  // fetch and await go here
}
nacti();

把数据显示在页面上

控制台给程序员——访客要在页面上看:

<p id="teplota">Loading…</p>

<script type="module">
  const odpoved = await fetch('https://api.open-meteo.com/v1/forecast?latitude=49.19&longitude=16.61&current_weather=true');
  const data = await odpoved.json();

  document.querySelector('#teplota').textContent =
    `Right now it's ${data.current_weather.temperature} °C`;
</script>

魔法师熟悉的(querySelectortextContent)加上新的 fetch。就这些。

轮到你了 💪

  1. 给网站加带 id="teplota" 的段落和上面脚本。
  2. 坐标改成你的城市。
  3. 显示里也加上 风速data.current_weather.windspeed)。
  4. 加分:温度低于 0 时在文字里加 ”🥶 Bundle up!”。

检查一下: 加载后页面上出现真实当前温度。关 Wi-Fi 刷新还停在 “Loading…”——证明数据真从网上来。

这堂课你要记住