上一篇
小明最近在开发一个天气预报小程序,需要从后端获取JSON格式的天气数据,然后动态展示在页面上,他听说Ajax可以异步获取数据而不用刷新整个页面,但具体怎么实现呢?今天我们就来手把手教你如何用Ajax获取JSON数据并动态展示在网页上。
我们需要了解几个关键概念:
下面是一个完整的示例,从获取数据到展示的全过程:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0">Ajax获取JSON数据示例</title> <style> body { font-family: 'Arial', sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; } .user-card { border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin-bottom: 10px; background-color: #f9f9f9; } .loading { text-align: center; font-style: italic; color: #666; } button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } button:hover { background-color: #45a049; } </style> </head> <body> <h1>用户信息展示</h1> <button id="loadDataBtn">加载用户数据</button> <div id="userContainer"> <p class="loading">点击上方按钮加载用户数据...</p> </div> <script> document.getElementById('loadDataBtn').addEventListener('click', function() { // 显示加载状态 const container = document.getElementById('userContainer'); container.innerHTML = '<p class="loading">正在加载数据,请稍候...</p>'; // 创建XMLHttpRequest对象 const xhr = new XMLHttpRequest(); // 配置请求 xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true); // 设置响应类型为JSON xhr.responseType = 'json'; // 请求完成时的回调 xhr.onload = function() { if (xhr.status === 200) { // 请求成功 const users = xhr.response; displayUsers(users); } else { // 请求失败 container.innerHTML = '<p style="color:red">加载数据失败,请重试</p>'; } }; // 网络错误处理 xhr.onerror = function() { container.innerHTML = '<p style="color:red">网络错误,请检查连接</p>'; }; // 发送请求 xhr.send(); }); // 展示用户数据的函数 function displayUsers(users) { const container = document.getElementById('userContainer'); if (users.length === 0) { container.innerHTML = '<p>没有找到用户数据</p>'; return; } let html = ''; users.forEach(user => { html += ` <div class="user-card"> <h3>${user.name}</h3> <p><strong>用户名:</strong> ${user.username}</p> <p><strong>邮箱:</strong> ${user.email}</p> <p><strong>电话:</strong> ${user.phone}</p> <p><strong>公司:</strong> ${user.company.name}</p> <p><strong>地址:</strong> ${user.address.street}, ${user.address.city}</p> </div> `; }); container.innerHTML = html; } </script> </body> </html>
我们创建了一个简单的页面,包含:- 一个触发加载数据的按钮
添加了一些基本样式使页面看起来更美观:
核心部分分为几个步骤:
监听按钮点击事件
document.getElementById('loadDataBtn').addEventListener('click', function() { // 点击后的操作 });
创建并配置XMLHttpRequest对象
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true); xhr.responseType = 'json';
这里我们:
处理响应
xhr.onload = function() { if (xhr.status === 200) { const users = xhr.response; displayUsers(users); } else { // 错误处理 } };
错误处理
xhr.onerror = function() { container.innerHTML = '<p style="color:red">网络错误,请检查连接</p>'; };
发送请求
xhr.send();
数据展示函数
function displayUsers(users) { // 遍历用户数据并生成HTML users.forEach(user => { html += ` <div class="user-card"> <h3>${user.name}</h3> <p><strong>用户名:</strong> ${user.username}</p> <!-- 其他用户信息 --> </div> `; }); container.innerHTML = html; }
跨域问题:如果请求的API和你的网站不同源,可能会遇到跨域限制,在实际项目中,你可能需要:
加载状态:良好的用户体验应该包含加载状态提示,就像我们示例中做的那样。
错误处理:网络请求可能会失败,完善的错误处理很重要。
现代替代方案:虽然我们使用了传统的XMLHttpRequest,但现在更推荐使用Fetch API或axios库,它们提供了更简洁的语法。
如果你想使用更现代的Fetch API,可以这样改写:
document.getElementById('loadDataBtn').addEventListener('click', async function() { const container = document.getElementById('userContainer'); container.innerHTML = '<p class="loading">正在加载数据,请稍候...</p>'; try { const response = await fetch('https://jsonplaceholder.typicode.com/users'); if (!response.ok) { throw new Error('网络响应不正常'); } const users = await response.json(); displayUsers(users); } catch (error) { container.innerHTML = `<p style="color:red">加载失败: ${error.message}</p>`; } });
通过这个示例,我们学会了:
现在你可以尝试修改这个示例,
Ajax是现代Web开发的基础技能之一,掌握它将为你的前端开发之路打下坚实基础。
本文由 罗舒 于2025-08-02发表在【云服务器提供商】,文中图片由(罗舒)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/518413.html
发表评论