气温快报
javascript
// 定义 API 密钥和天气 API URL
const API_KEY = 'YOUR_API_KEY';
const WEATHER_API_URL = 'https://api.openweathermap.org/data/2.5/weather';
const FORECAST_API_URL = 'https://api.openweathermap.org/data/2.5/forecast';// 获取天气数据
async function getWeatherData(city) {const response = await fetch(`${WEATHER_API_URL}?q=${city}&appid=${API_KEY}`);return await response.json();
}// 获取天气预报数据
async function getForecastData(city) {const response = await fetch(`${FORECAST_API_URL}?q=${city}&appid=${API_KEY}`);return await response.json();
}// 显示当前天气
function displayCurrentWeather(data) {const temperature = Math.round(data.main.temp - 273.15);const conditions = data.weather[0].main;document.getElementById('weather-temperature').innerHTML = `${temperature}°C`;document.getElementById('weather-conditions').innerHTML = conditions;
}// 显示未来天气预报
function displayForecast(data) {const forecastList= document.getElementById('weather-forecast-list');data.list.forEach((forecast) => {const date = new Date(forecast.dt 1000);const temperature = Math.round(forecast.main.temp - 273.15);const conditions = forecast.weather[0].main;const forecastItem = document.createElement('li');forecastItem.innerHTML = `
${date.toLocaleDateString()}
${temperature}°C
${conditions}
`;forecastList.appendChild(forecastItem);});
}// 获取并显示天气数据
function init() {const city = prompt('请输入城市名称:');getWeatherData(city).then((data) => displayCurrentWeather(data));getForecastData(city).then((data) => displayForecast(data));
}init();