<div class="container">
<h2>城市天气查询</h2>
<div class="input-group">
<input type="text" id="city" placeholder="请输入城市名称 (例如: 北京)">
<button onclick="queryWeather()">查询</button>
</div>
<div id="result" class="weather-box"></div>
</div>
<script>
const APP_ID = "1951410"; // 修正:添加了必需的APP_ID
const APP_KEY = "5904dDf6Aa6F435bb822bbdb069A15e5";
const API_URL = "https://route.showapi.com/9-2";
async function queryWeather() {
const city = document.getElementById("city").value.trim();
const resultDom = document.getElementById("result");
if (!city) {
resultDom.innerHTML = "<p class='error'>请输入城市名</p>";
return;
}
resultDom.innerHTML = "<p class='loading'>正在查询天气...</p>";
try {
const params = new URLSearchParams({
// 修正:添加了缺失的 showapi_appid 参数
showapi_appid: APP_ID,
showapi_sign: APP_KEY,
area: city,
});
const response = await fetch(`${API_URL}?${params}`);
const data = await response.json();
if (data.showapi_res_code === 0) {
const weatherInfo = data.showapi_res_body;
const today = weatherInfo.f1;
resultDom.innerHTML = `
<p>城市:${weatherInfo.cityInfo.c3}</p>
<p>日期:${today.day}</p>
<p>天气:${today.day_weather}</p>
<p>温度:${today.day_air_temperature}</p>
<p>风向:${today.day_wind_direction}</p>
<p>日出时间:${today.sun_begin_end.split('-')[0]}</p>
<p>日落时间:${today.sun_begin_end.split('-')[1]}</p>
`;
} else {
resultDom.innerHTML = `<p class='error'>错误:${data.showapi_res_error || '查询失败'}</p>`;
}
} catch (error) {
resultDom.innerHTML = `<p class='error'>网络错误:${error.message}</p>`;
}
}
// 页面加载时默认查询
window.onload = queryWeather;
</script>
