如何在HTML页面展示OpenWeatherMap API查询的Morgins天气数据?
如何在HTML页面展示OpenWeatherMap API的天气数据?
看起来你已经搞定了OpenWeatherMap的API请求地址,接下来只需要完成XML响应解析和页面渲染这两步就行,我给你整理了完整的实现方案,完美适配你用的XML模式:
1. 先完善HTML结构
首先给页面加个专门的容器用来放天气数据,顺便加一点基础样式让页面看着舒服些:
<!DOCTYPE html> <html> <head> <title>Morgins Weather Forecast</title> <style> .weather-card { border: 1px solid #eee; padding: 15px; margin: 10px; border-radius: 8px; width: 200px; display: inline-block; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .weather-date { font-weight: bold; margin-bottom: 8px; color: #2c3e50; } .weather-temp { font-size: 1.3em; color: #e74c3c; margin: 8px 0; } </style> </head> <body> <h1>Morgins 7日天气预报</h1> <button onclick="getWeather()">点击获取天气</button> <!-- 天气数据展示容器 --> <div id="weatherContainer"></div> <script> // 后续JS代码写在这里 </script> </body> </html>
2. 完成JavaScript的API请求与解析
因为你用了mode=xml,所以要专门处理XML格式的响应,把你的getWeather函数改成这样:
function getWeather() { const container = document.getElementById('weatherContainer'); container.innerHTML = '<p>正在加载天气数据...</p>'; // 补全你的API地址,建议用HTTPS避免跨域问题 const url = 'https://api.openweathermap.org/data/2.5/forecast/daily?q=morgins&APPID=001b0f58045147663b1ea518d34d88b4&mode=xml&units=metric&cnt=7'; const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onload = function() { if (this.status >= 200 && this.status < 400) { // 解析返回的XML数据 const xmlDoc = this.responseXML; const dailyForecasts = xmlDoc.getElementsByTagName('time'); container.innerHTML = ''; // 清空加载提示 // 遍历每一天的天气数据,生成卡片 for (let i = 0; i < dailyForecasts.length; i++) { const forecast = dailyForecasts[i]; const date = forecast.getAttribute('day'); const dayTemp = forecast.getElementsByTagName('temp')[0].getAttribute('day'); const weatherDesc = forecast.getElementsByTagName('weather')[0].getAttribute('value'); const weatherIcon = forecast.getElementsByTagName('weather')[0].getAttribute('icon'); // 创建单个天气卡片 const card = document.createElement('div'); card.className = 'weather-card'; card.innerHTML = ` <div class="weather-date">${date}</div> <img src="http://openweathermap.org/img/wn/${weatherIcon}@2x.png" alt="${weatherDesc}" width="60"> <div class="weather-temp">${dayTemp}°C</div> <div>${weatherDesc}</div> `; container.appendChild(card); } } else { container.innerHTML = '<p>获取天气数据失败,请检查API密钥或请求地址是否正确</p>'; } }; xhr.onerror = function() { container.innerHTML = '<p>网络请求出错,请检查网络连接</p>'; }; xhr.send(); }
3. 解决Chrome本地测试的跨域问题
如果你直接双击HTML文件用Chrome打开(file://协议),浏览器会因为跨域策略阻止API请求,给你两个解决办法:
- 方法一:启动Chrome时临时关闭跨域验证。Windows用户打开命令提示符执行:
Mac用户打开终端执行:"C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/ChromeDevSession"open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --disable-web-security --user-data-dir="/tmp/ChromeDevSession" - 方法二:用本地服务器运行HTML。比如用Python的简易服务器,在项目目录打开终端执行:
然后在Chrome里访问# Python 3版本 python -m http.server 8000http://localhost:8000/你的文件名.html,这样就不会有跨域问题了。
内容的提问来源于stack exchange,提问作者James Miller




