Skip to content

Weather Lookup

中等 约 25 分钟

你将构建什么

page 使用 city 搜索输入. 输入 city name and 点击搜索获取 weather 数据从 free API and displays temperature and 条件.

学习目标

  • Use 获取使用异步/等待到 获取 weather 数据
  • Parse JSON 响应 and extract relevant 字段
  • Handle 错误 (city 不找到, network 失败)
  • 更新 DOM 使用 weather 信息

前置要求

  • 异步/等待 and Promise
  • 获取 API 基础
  • DOM selection and 事件监听器

步骤

  1. 1

    创建 HTML

    创建搜索输入, 搜索 button, and result div. result div 将 show weather 信息.

    代码
    <input id="city" placeholder="Enter city name">
    <button id="search">Search</button>
    <div id="result">Weather will appear here</div>

    预期结果

    搜索输入, button, and result 区域 appear.

  2. 2

    编写获取函数

    编写异步函数那个获取 weather 数据从 free API (e.g., 打开-Meteo). Use try/catch for 错误 handling.

    代码
    async function getWeather(city) {
      const url = `https://geocoding-api.open-meteo.com/v1/search?name=${city}&count=1`;
      const geoRes = await fetch(url);
      const geo = await geoRes.json();
      if (!geo.results || !geo.results[0]) throw new Error("City not found");
      const { latitude, longitude } = geo.results[0];
      const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m`;
      const wRes = await fetch(weatherUrl);
      const w = await wRes.json();
      return w.current.temperature_2m;
    }

    预期结果

    Calling getWeather('London') 返回 current temperature.

  3. 3

    Wire 搜索 button

    添加点击监听器那个读取 city 输入, calls getWeather, and 更新 result div. Handle 错误 gracefully.

    代码
    const resultEl = document.getElementById("result");
    document.getElementById("search").addEventListener("click", async () => {
      const city = document.getElementById("city").value.trim();
      if (!city) return;
      resultEl.textContent = "Loading...";
      try {
        const temp = await getWeather(city);
        resultEl.textContent = `Temperature in ${city}: ${temp}°C`;
      } catch (err) {
        resultEl.textContent = `Error: ${err.message}`;
      }
    });

    预期结果

    搜索 for city shows 它的 current temperature, or 错误消息如果不 找到.

  4. 4

    添加输入验证与错误处理

    在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 try/catch 或条件判断给出友好提示。健壮的 JS 程序不会因意外输入而崩溃。

    代码
    function safeParse(value) {
      if (value === null || value === undefined || value === "") {
        throw new Error("Input is empty");
      }
      const num = Number(value);
      if (Number.isNaN(num)) {
        throw new Error(`"${value}" is not a valid number`);
      }
      return num;
    }
    
    try {
      const n = safeParse(userInput);
      process(n);
    } catch (err) {
      console.error(err.message);
    }

    预期结果

    空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。

  5. 5

    添加事件监听与交互

    为页面元素绑定事件监听器(click、input、keydown 等),让程序响应用户操作。交互性是 JavaScript 在前端的核心价值。

    代码
    const button = document.querySelector("#action-btn");
    const input = document.querySelector("#user-input");
    
    button.addEventListener("click", () => {
      const value = input.value.trim();
      if (!value) return;
      runMainLogic(value);
    });
    
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") button.click();
    });

    预期结果

    点击按钮或按回车键触发主逻辑;空输入被忽略。

自己动手试试

你学到了什么

你 used 异步/等待使用获取到 retrieve 真实数据从 API, parsed JSON 响应, and handled 错误使用 try/catch — 标准模式 for 任何 web app 那个 talks 到服务器.

相关资源

相关课程

相关练习

相关速查表

相关错误

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题