首先获取天气api密钥,然后通过javascript调用api并解析json数据,最后将结果动态显示在网页上。具体步骤包括:注册openweathermap等平台获取密钥,创建html容器展示信息,使用fetch请求天气数据并处理响应,结合城市名或地理位置实时更新温度、湿度、风速等内容,还可添加输入框、定时刷新和天气图标增强交互体验。注意控制请求频率以避免超出免费限额。

要在网页中实现动态天气显示,核心是调用天气API并使用JavaScript处理返回数据。整个过程包括获取API密钥、发送请求、解析JSON数据,并将结果显示在页面上。下面详细介绍具体步骤和代码示例。
1. 选择并注册天气API服务
常用的免费天气API有:
- OpenWeatherMap:提供实时天气、预报、地理编码等功能,注册后可获得免费API密钥。
- WeatherAPI:支持多语言、空气质量等数据,也有免费套餐。
- 高德地图开放平台(国内推荐):中文支持好,响应快,适合中国城市。
以 OpenWeatherMap 为例,访问官网(openweathermap.org)注册账号,进入“API Keys”页面获取你的密钥(如:your_api_key)。
2. 编写HTML结构
创建一个简单的页面容器用于展示天气信息:
<div id="weather">
<p>正在加载天气...</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2158" title="拍我AI"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175680310874179.png" alt="拍我AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2158" title="拍我AI">拍我AI</a>
<p>AI视频生成平台PixVerse的国内版本</p>
</div>
<a href="/ai/2158" title="拍我AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
</div>
3. 使用JavaScript调用API并更新页面
通过fetch()方法请求OpenWeatherMap的实时天气接口(当前天气数据API):
<script> // 示例脚本:获取指定城市的天气 function getWeather(city = 'Beijing') { const apiKey = 'your_api_key'; // 替换为你的实际密钥 const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&lang=zh_cn&appid=${apiKey}`; fetch(url) .then(response => { if (!response.ok) throw new Error('城市未找到或网络错误'); return response.<a style="color:#f60; text-decoration:underline;" title= "js" href="https://www.php.cn/zt/15802.html" target="_blank">json(); }) .then(data => { const weatherDiv = document.getElementById('weather'); weatherDiv.innerHTML = ` <strong>${data.name}:${Math.round(data.m<a style="color:#f60; text-decoration:underline;" title= "ai" href="https://www.php.cn/zt/17539.html" target="_blank">ain.temp)}°C,${data.weather[0].description} <br>湿度:${data.main.humidity}%,风速:${data.<a style="color:#f60; text-decoration:underline;" title= "win" href="https://www.php.cn/zt/19041.html" target="_blank">wind.speed} m/s `; }) .catch(error => { document.getElementById('weather').innerHTML = `天气加载失败:${error.message}`; }); } // 页面加载完成后执行 window.onload = () => getWeather(); </script>说明:
- q=${city} 表示查询的城市名称。
- units=metric 使用摄氏度(否则默认为开尔文)。
- lang=zh_cn 启用中文描述(部分API支持)。
- 返回的JSON包含温度、天气描述、湿度、风速等字段。
4. 增强功能建议
让天气显示更实用和动态:
- 添加输入框让用户切换城市:
- 加入地理位置定位自动获取本地天气:
使用navigator.geolocation获取经纬度,改用lat和lon参数请求。 - 定时刷新天气(每10分钟):
setInterval(() => getWeather(), 600000); - 添加图标显示天气状况(如晴天、雨天),可结合开源图标库(如 Weather Icons)。
基本上就这些。只要正确配置API密钥并处理好异步请求,就能实现一个简洁美观的动态天气模块。注意避免频繁请求防止超出免费额度,上线前做好错误提示和加载状态优化。









