Weather Lookup
你将构建什么
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
创建 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
编写获取函数
编写异步函数那个获取 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}¤t=temperature_2m`; const wRes = await fetch(weatherUrl); const w = await wRes.json(); return w.current.temperature_2m; }预期结果
Calling getWeather('London') 返回 current temperature.
提示
打开-Meteo 是 free weather API 那个需要否 API 键.
- 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
添加输入验证与错误处理
在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 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
添加事件监听与交互
为页面元素绑定事件监听器(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(); });预期结果
点击按钮或按回车键触发主逻辑;空输入被忽略。
自己动手试试
<input id="city" placeholder="Enter city name">
<button id="search">Search</button>
<div id="result">Weather will appear here</div>
<script>
// TODO: getWeather function + wire search button
</script><input id="city" placeholder="Enter city name">
<button id="search">Search</button>
<div id="result">Weather will appear here</div>
<script>
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}¤t=temperature_2m`;
const wRes = await fetch(weatherUrl);
const w = await wRes.json();
return w.current.temperature_2m;
}
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}`;
}
});
</script>你学到了什么
你 used 异步/等待使用获取到 retrieve 真实数据从 API, parsed JSON 响应, and handled 错误使用 try/catch — 标准模式 for 任何 web app 那个 talks 到服务器.
相关资源
相关课程
- 异步 JavaScript
异步/等待 and 获取.
- DOM
更新 DOM 使用 results.
相关练习
- Predict 异步/等待输出
练习 predicting 异步/等待 results.
相关速查表
- JavaScript Cheatsheet
获取 and 异步/等待引用.
相关错误
- Promise 不 Awaited
常见异步错误.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- Promise 不 Awaited
常见异步错误.