html如何取天气

要获取天气信息,可以使用HTML和JavaScript结合的方式,你需要找到一个提供天气数据的API,例如OpenWeatherMap、Weather API等,使用JavaScript发起请求并处理返回的数据,将数据显示在HTML页面上。,以下是一个简单的示例:,1、注册一个免费账户并获取API密钥(以OpenWeatherMap为例):https://openweathermap.org/appid,2、创建一个HTML文件,如
weather.html,并添加以下内容:,3、创建一个JavaScript文件,如
weather.js,并添加以下内容:,4、用浏览器打开
weather.html文件,输入城市名称并点击查询按钮,即可显示该城市的实时天气信息。,
,<!DOCTYPE html> <html lang=”zh”> <head> <meta charset=”UTF8″> <meta name=”viewport” content=”width=devicewidth, initialscale=1.0″> <title>天气查询</title> </head> <body> <h1>实时天气查询</h1> <input type=”text” id=”city” placeholder=”请输入城市名称”> <button onclick=”getWeather()”>查询</button> <table border=”1″> <tr> <th>城市</th> <th>温度</th> <th>天气描述</th> </tr> <tr> <td id=”cityName”></td> <td id=”temperature”></td> <td id=”description”></td> </tr> </table> <script src=”weather.js”></script> </body> </html>,const apiKey = ‘你的API密钥’; // 替换为你的API密钥 function getWeather() { const city = document.getelementbyid(‘city’).value; if (!city) { alert(‘请输入城市名称’); return; } const url =
https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=zh_cn; fetch(url) .then(response => response.json()) .then(data => { document.getElementById(‘cityName’).innerText = data.name; document.getElementById(‘temperature’).innerText = data.main.temp + ‘°C’; document.getElementById(‘description’).innerText = data.weather[0].description; }) .catch(error => { console.error(‘获取天气信息失败:’, error); alert(‘获取天气信息失败,请检查城市名称是否正确’); }); },

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《html如何取天气》
文章链接:https://zhuji.vsping.com/426869.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。