基于JavaScript与HTML的OpenWeatherMap API城市天气查询问题求助
天气搜索功能动态获取城市名失效问题修复
问题背景
具备基础JavaScript与HTML知识,想要实现类天气搜索功能,采用OpenWeatherMap免费API。此前在Data.js中固定指定城市(如Tokyo)时功能正常,但改为动态获取城市名后功能失效,寻求技术帮助。
原代码
HTML代码
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name=""viewport" content=""width-device-width, initial-scale=1"> <title>My weather app</title> </head> <body> <form> <input type="text" id="cityName" placeholder="Enter a city name"><br> <input type="submit" value="Get Weather Information" id="weather_data"> </form> <div id="display_data"></div> <h1 id=city_name"> Please wait...</h1> <p id="myParagraph">Please wait...</p> <img id="icon" src = "" alt = "Weather icon"> <p id="myTemp"> Please wait...</p> <p id="minimum">Please wait...</p> <p id="maximum">Please wait...</p> <script src="City_Name.js"></script> <script src="Data.js"></script> </body> </html>
City_Name.js代码
// Fetch Wweather data from API and searching for a city var weatherData = document.getElementById("weather_data"); weatherData.addEventListener('click',function(e){ e.preventDefault(); var cityName = document.getElementById("cityName").value; var url = "https://api.openweathermap.org/data/2.5/weather?q="+cityName+"&appid={API Key}" if(cityName == ""){ alert("Enter a city name"); }else{ fetch(url).then(function(response){ if(response.ok){ return response.json(); }else{ throw new Error(Error); } }).then(function(data){ console.log(data); const html = ` <h2 class="text-danger text-center"><span class="text-dark">City:</span>${data.name}</h2> ` ; document.getElementById("display_data").insertAdjacentHTML('afterbegin',html); }).catch(function(error){ console.log(error); }); } });
Data.js代码
// Fetching City_Name to the script include('City_Name.js') // Fetch API fetch('https://api.openweathermap.org/data/2.5/weather?q='+cityName+'&appid={API Key') // Convert response string to json object .then(response => response.json()) .then(response => { // Display whole API response in browser console (take a look at it!) console.log(response); // Copy one element of response to our HTML paragraph document.getElementById("myParagraph").innerHTML ="The weather is: " + response.weather[0].description; document.getElementById("icon").src = "https://openweathermap.org/img/wn/" + response.weather[0].icon + "@2x.png"; document.getElementById("myTemp").innerHTML = "The temperature is: " + response.main.temp + " °C"; document.getElementById("minimum").innerHTML = "The minimum temperature should be: " + response.main.temp_min; document.getElementById("maximum").innerHTML = "The minimum temperature should be: " + response.main.temp_max; }) .catch(err => { // Display errors in console console.log(err); });
问题分析
- 脚本与变量问题:Data.js里的
include('City_Name.js')是无效语法——浏览器原生JS没有这个方法,且HTML已经引入了两个脚本。同时Data.js在页面加载时就执行fetch,但cityName是City_Name.js点击事件内的局部变量,此时根本不存在,导致请求URL错误。 - 逻辑冗余:两个脚本都发起API请求,重复操作且时机错误。
- 语法错误:HTML里
<h1 id=city_name">引号不匹配;Data.js的API URL末尾缺失闭合的}。 - 温度单位问题:OpenWeatherMap返回的是开尔文温度,直接显示不符合用户习惯。
修复方案
合并脚本逻辑,修正语法错误,调整请求与渲染逻辑:
修正后的HTML代码
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My weather app</title> </head> <body> <form> <input type="text" id="cityName" placeholder="Enter a city name"><br> <input type="submit" value="Get Weather Information" id="weather_data"> </form> <div id="display_data"></div> <h1 id="city_name">Please wait...</h1> <p id="myParagraph">Please wait...</p> <img id="icon" src="" alt="Weather icon"> <p id="myTemp">Please wait...</p> <p id="minimum">Please wait...</p> <p id="maximum">Please wait...</p> <script src="WeatherApp.js"></script> </body> </html>
合并后的WeatherApp.js代码
// 绑定搜索按钮点击事件 const weatherDataBtn = document.getElementById("weather_data"); weatherDataBtn.addEventListener('click', function(e){ e.preventDefault(); const cityName = document.getElementById("cityName").value.trim(); const apiKey = "{你的API Key}"; // 替换成你的OpenWeatherMap API Key const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}`; // 校验输入是否为空 if(!cityName){ alert("请输入城市名称"); return; } fetch(url) .then(function(response){ if(response.ok){ return response.json(); }else{ throw new Error(`请求失败,状态码:${response.status}`); } }) .then(function(data){ console.log(data); // 渲染城市名称(替换原有内容,避免重复添加) const cityHtml = `<h2 class="text-danger text-center"><span class="text-dark">City:</span>${data.name}</h2>`; document.getElementById("display_data").innerHTML = cityHtml; // 渲染天气详情 document.getElementById("city_name").textContent = data.name; document.getElementById("myParagraph").textContent = `天气状况:${data.weather[0].description}`; document.getElementById("icon").src = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`; // 开尔文转摄氏度,保留两位小数 const tempCelsius = (data.main.temp - 273.15).toFixed(2); const minTempCelsius = (data.main.temp_min - 273.15).toFixed(2); const maxTempCelsius = (data.main.temp_max - 273.15).toFixed(2); document.getElementById("myTemp").textContent = `当前温度:${tempCelsius} °C`; document.getElementById("minimum").textContent = `最低温度:${minTempCelsius} °C`; document.getElementById("maximum").textContent = `最高温度:${maxTempCelsius} °C`; }) .catch(function(error){ console.error(error); alert("获取天气信息失败,请检查城市名称或网络连接"); }); });
修改说明
- 移除无效的
include语句,合并两个脚本的逻辑,确保只有点击按钮时才发起请求,变量作用域正确。 - 修正HTML和API URL的语法错误。
- 添加输入内容去空格处理,避免空字符请求。
- 将开尔文温度转换为摄氏度,提升显示可读性。
- 用
innerHTML替换insertAdjacentHTML,避免多次点击重复添加城市名称。 - 完善错误提示,包括请求状态码和用户友好的弹窗提示。
内容的提问来源于stack exchange,提问作者Josh Smith
相关产品推荐
相关产品推荐

