-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
59 lines (47 loc) · 2.16 KB
/
script.js
File metadata and controls
59 lines (47 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// THAY THẾ 'YOUR_API_KEY' BẰNG KHÓA API THỰC TẾ CỦA BẠN TỪ OpenWeatherMap
const API_KEY = '55b90b675d89f6ce90b257906240e49e';
document.getElementById('search-button').addEventListener('click', () => {
const city = document.getElementById('city-input').value.trim();
if (city) {
fetchWeather(city);
} else {
displayError('Vui lòng nhập tên thành phố.');
}
});
async function fetchWeather(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric&lang=vi`;
try {
const response = await fetch(url);
// Kiểm tra lỗi HTTP (ví dụ: 404 Not Found, 401 Unauthorized)
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Không tìm thấy thành phố hoặc lỗi: ${errorData.message}`);
}
const data = await response.json();
displayWeather(data);
} catch (error) {
// Xử lý lỗi kết nối hoặc lỗi từ API
displayError(error.message);
}
}
function displayWeather(data) {
// Ẩn thông báo lỗi nếu có
document.getElementById('error-message').classList.add('hidden');
// Hiển thị khung kết quả
const resultDiv = document.getElementById('weather-result');
resultDiv.classList.remove('hidden');
// Chuyển đổi nhiệt độ từ Kelvin/Celsius sang hiển thị
const temperature = data.main.temp;
document.getElementById('city-name').textContent = `Thời tiết tại ${data.name}`;
document.getElementById('temperature').textContent = `Nhiệt độ: ${temperature}°C`;
document.getElementById('description').textContent = `Mô tả: ${data.weather[0].description}`;
document.getElementById('humidity').textContent = `Độ ẩm: ${data.main.humidity}%`;
}
function displayError(message) {
// Ẩn kết quả nếu có lỗi
document.getElementById('weather-result').classList.add('hidden');
// Hiển thị thông báo lỗi
const errorMsg = document.getElementById('error-message');
errorMsg.textContent = `Lỗi: ${message}`;
errorMsg.classList.remove('hidden');
}