js实现天气
使用 JavaScript 实现天气功能
获取天气 API
选择一个可靠的天气 API 服务,如 OpenWeatherMap、WeatherAPI 或 AccuWeather。这些服务通常提供免费的开发套餐,适合小型项目。注册账号后获取 API 密钥。
发起 API 请求
使用 fetch 或 axios 发起 HTTP 请求获取天气数据。以下是使用 fetch 的示例代码:
const apiKey = 'YOUR_API_KEY';
const city = 'Beijing';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data);
displayWeather(data);
})
.catch(error => console.error('Error:', error));
解析并显示天气数据
从 API 返回的数据中提取所需信息,如温度、湿度、天气描述等,并将其显示在页面上。

function displayWeather(data) {
const weatherDiv = document.getElementById('weather');
const temp = data.main.temp;
const humidity = data.main.humidity;
const description = data.weather[0].description;
weatherDiv.innerHTML = `
<h3>Weather in ${data.name}</h3>
<p>Temperature: ${temp}°C</p>
<p>Humidity: ${humidity}%</p>
<p>Description: ${description}</p>
`;
}
处理用户输入
允许用户输入城市名称并触发天气查询。可以通过表单和事件监听器实现。
document.getElementById('weatherForm').addEventListener('submit', function(e) {
e.preventDefault();
const city = document.getElementById('cityInput').value;
getWeather(city);
});
错误处理
确保在 API 请求失败或用户输入无效时提供友好的错误提示。

function getWeather(city) {
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('City not found');
}
return response.json();
})
.then(data => displayWeather(data))
.catch(error => {
document.getElementById('weather').innerHTML = `<p>${error.message}</p>`;
});
}
示例 HTML 结构
以下是一个简单的 HTML 结构,用于显示天气信息和用户输入表单。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather App</title>
</head>
<body>
<form id="weatherForm">
<input type="text" id="cityInput" placeholder="Enter city name" required>
<button type="submit">Get Weather</button>
</form>
<div id="weather"></div>
<script src="weather.js"></script>
</body>
</html>
完整代码示例
将上述代码整合到一个文件中,确保替换 YOUR_API_KEY 为实际的 API 密钥。
// weather.js
document.getElementById('weatherForm').addEventListener('submit', function(e) {
e.preventDefault();
const city = document.getElementById('cityInput').value;
getWeather(city);
});
function getWeather(city) {
const apiKey = 'YOUR_API_KEY';
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('City not found');
}
return response.json();
})
.then(data => displayWeather(data))
.catch(error => {
document.getElementById('weather').innerHTML = `<p>${error.message}</p>`;
});
}
function displayWeather(data) {
const weatherDiv = document.getElementById('weather');
const temp = data.main.temp;
const humidity = data.main.humidity;
const description = data.weather[0].description;
weatherDiv.innerHTML = `
<h3>Weather in ${data.name}</h3>
<p>Temperature: ${temp}°C</p>
<p>Humidity: ${humidity}%</p>
<p>Description: ${description}</p>
`;
}
通过以上步骤,可以实现一个简单的天气查询功能。根据需求可以进一步扩展,如添加图标、更多天气细节或缓存机制。






