
在从api获取数据之前,首先需要了解api返回的数据结构。一个典型的天气api响应通常是一个json对象,其中包含多个嵌套的对象和数组。例如,我们所使用的api(https://mm214.com/jsondemo.php)可能返回类似以下结构的json数据:
{
"coord": { /* ... */ },
"weather": [{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle", // 我们需要的天气描述
"icon": "09d"
}],
"base": "stations",
"main": {
"temp": 280.32, // 我们需要的温度
"pressure": 1012,
"humidity": 81,
"temp_min": 279.15,
"temp_max": 281.15
},
"visibility": 10000,
"wind": { /* ... */ },
"clouds": { /* ... */ },
"dt": 1485789600,
"sys": { /* ... */ },
"id": 2643743,
"name": "London",
"cod": 200
}从上述结构中,我们可以看到:
理解这种嵌套结构是正确获取数据的关键。
XMLHttpRequest (XHR) 是浏览器内置的API,用于在不重新加载页面的情况下向服务器发送HTTP请求和接收响应。以下是一个封装了XHR请求的 getJSON 函数:
const getJSON = function(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // 初始化请求,使用GET方法,并设置为异步
xhr.responseType = 'json'; // 期望服务器响应的数据类型为JSON
// 监听请求状态变化或响应加载完成
xhr.onload = function() {
let status = xhr.status;
if (status === 200) { // HTTP状态码200表示请求成功
callback(null, xhr.response); // 调用回调函数,传递null作为错误,xhr.response作为数据
} else {
callback(status); // 如果状态码不是200,传递状态码作为错误
}
};
// 监听网络错误或CORS问题
xhr.onerror = function() {
callback('Network error or CORS issue');
};
xhr.send(); // 发送请求
};代码解析:
立即学习“Java免费学习笔记(深入)”;
为了在网页上显示获取到的温度和天气描述,我们需要在HTML中准备相应的占位符元素。通常使用 <span> 标签并赋予唯一的 id。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>当前天气信息</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
#weather-display { border: 1px solid #e0e0e0; padding: 15px; border-radius: 8px; max-width: 350px; background-color: #f9f9f9; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
#weather-display div { margin-bottom: 10px; display: flex; align-items: center; }
#weather-display strong { display: inline-block; width: 80px; color: #333; font-size: 1.1em; }
#temp, #weather-description { font-weight: bold; color: #007bff; font-size: 1.1em; }
h1 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; margin-bottom: 20px; }
</style>
</head>
<body>
<h1>当前天气信息</h1>
<div id="weather-display">
<div><strong>温度:</strong> <span id="temp">加载中...</span></div>
<div><strong>描述:</strong> <span id="weather-description">加载中...</span></div>
</div>
<script>
// getJSON 函数定义同上
const getJSON = function(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
let status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.onerror = function() {
callback('Network error or CORS issue');
};
xhr.send();
};
// 您的API端点
const API_URL = 'https://mm214.com/jsondemo.php';
getJSON(API_URL, function(err, data) {
const tempElement = document.getElementById("temp");
const weatherDescElement = document.getElementById("weather-description");
if (err) {
console.error('获取天气数据失败:', err);
if (tempElement) tempElement.innerHTML = '获取失败';
if (weatherDescElement) weatherDescElement.innerHTML = '获取失败';
alert('获取天气数据时发生错误: ' + err);
} else {
// 确保数据存在且结构正确
if (data && data.main && typeof data.main.temp !== 'undefined') {
// 假设API返回开尔文温度,可根据需要转换为摄氏度或华氏度
if (tempElement) tempElement.innerHTML = data.main.temp + ' K';
} else {
if (tempElement) tempElement.innerHTML = 'N/A';
}
// weather是一个数组,通常第一个元素包含主要的天气描述
if (data && data.weather && data.weather.length > 0 && data.weather[0].description) {
if (weatherDescElement) weatherDescElement.innerHTML = data.weather[0].description;
} else {
if (weatherDescElement) weatherDescElement.innerHTML = 'N/A';
}
}
});
</script>
</body>
</html>关键点:
错误处理: 始终实现健壮的错误处理机制。在 getJSON 函数中,我们处理了HTTP状态码非200的情况以及网络错误。在回调函数中,也应该优雅地显示错误信息给用户,而不是让页面崩溃。
API密钥: 许多公共API需要API密钥进行认证。在本示例中,API不需要密钥,但在实际项目中,请确保妥善管理和保护您的API密钥(例如,不要直接暴露在前端代码中,而通过后端代理请求)。
异步性理解: AJAX请求是异步的。这意味着 getJSON 函数会立即返回,而数据处理逻辑会在请求完成后(即 callback 被调用时)执行。
跨域资源共享 (CORS): 如果您的网页与API位于不同的域,浏览器可能会阻止请求,出现CORS错误。这通常需要服务器端配置来允许跨域请求。
温度单位转换: 不同的天气API可能返回不同的温度单位(如开尔文、摄氏度、华氏度)。在显示之前,请确保进行必要的单位转换以符合用户预期。
现代替代方案: 尽管 XMLHttpRequest 功能强大,但现代JavaScript开发中更推荐使用 Fetch API 或第三方库如 Axios,它们提供了更简洁、更Promise化的API来处理HTTP请求。例如:
// 使用Fetch API
fetch(API_URL)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
// 处理数据并更新DOM
document.getElementById("temp").innerHTML = data.main.temp + ' K';
document.getElementById("weather-description").innerHTML = data.weather[0].description;
})
.catch(error => {
console.error('获取天气数据失败:', error);
document.getElementById("temp").innerHTML = '获取失败';
document.getElementById("weather-description").innerHTML = '获取失败';
});通过本文,我们学习了如何使用原生JavaScript的 XMLHttpRequest 对象从API获取天气数据。关键在于理解API响应的JSON数据结构,特别是如何访问嵌套的对象属性和数组元素。通过清晰的HTML结构和JavaScript逻辑,我们可以轻松地将API数据动态地呈现在网页上,并结合错误处理和最佳实践,构建出健壮且用户友好的应用。虽然 XMLHttpRequest 是基础,了解现代的 Fetch API 也能帮助您编写更简洁高效的代码。
以上就是JavaScript原生AJAX实现天气API数据获取与展示:温度与描述的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号