![html如何取天气-国外主机测评 - 国外VPS,国外服务器,国外云服务器,测评及优惠码](https://zhuji.vsping.com/wp-content/uploads/2024/04/cdeaed5f8b5793a1f00000cc4e4ff748-220x150.jpg)
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(‘获取天气信息失败,请检查城市名称是否正确’); }); },