如何用Axios从phpMyAdmin取数并在纯前端表格展示(非React/Vue)
原生JS + Axios + PHP 从MySQL(phpMyAdmin)获取数据展示表格示例
1. 数据库准备(phpMyAdmin操作)
先在phpMyAdmin中完成以下配置:
- 创建数据库:
test_db - 创建表
users,字段包括:id(INT,主键,自增)name(VARCHAR(50))email(VARCHAR(100))age(INT)
- 插入测试数据,执行SQL语句:
INSERT INTO users (name, email, age) VALUES ('张三', 'zhangsan@example.com', 25), ('李四', 'lisi@example.com', 30), ('王五', 'wangwu@example.com', 28);
2. PHP后端接口(get_users.php)
该文件负责连接数据库、查询数据并返回JSON格式结果:
<?php // 数据库配置,根据你的实际环境修改 $host = 'localhost'; $dbname = 'test_db'; $username = 'root'; $password = ''; try { // 建立PDO连接 $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 查询所有用户数据 $stmt = $pdo->query("SELECT * FROM users"); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); // 返回JSON数据 header('Content-Type: application/json'); echo json_encode($users); } catch(PDOException $e) { // 错误处理 header('HTTP/1.1 500 Internal Server Error'); echo json_encode(array('error' => $e->getMessage())); } ?>
3. HTML前端(index.html)
包含CSS样式、Axios引入、表格结构和数据渲染逻辑:
<!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> table { width: 80%; margin: 20px auto; border-collapse: collapse; font-family: Arial, sans-serif; } th, td { border: 1px solid #ddd; padding: 12px; text-align: left; } th { background-color: #f2f2f2; font-weight: bold; } tr:hover { background-color: #f5f5f5; } .error-message { color: red; text-align: center; margin-top: 20px; } </style> <!-- 引入Axios CDN --> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <h1 style="text-align: center;">用户数据列表</h1> <table id="usersTable"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>邮箱</th> <th>年龄</th> </tr> </thead> <tbody> <!-- 数据将通过JS动态插入 --> </tbody> </table> <div id="error" class="error-message"></div> <script> // 页面加载完成后发起请求 document.addEventListener('DOMContentLoaded', function() { axios.get('get_users.php') .then(function(response) { const users = response.data; const tbody = document.querySelector('#usersTable tbody'); // 遍历数据生成表格行 users.forEach(user => { const row = document.createElement('tr'); row.innerHTML = ` <td>${user.id}</td> <td>${user.name}</td> <td>${user.email}</td> <td>${user.age}</td> `; tbody.appendChild(row); }); }) .catch(function(error) { const errorDiv = document.getElementById('error'); if (error.response) { errorDiv.textContent = '获取数据失败:' + error.response.data.error; } else { errorDiv.textContent = '请求出错,请检查网络或接口地址'; } }); }); </script> </body> </html>
运行说明
- 将
get_users.php和index.html放在Web服务器根目录(如XAMPP的htdocs文件夹) - 启动Web服务器和MySQL服务(如XAMPP的Apache、MySQL模块)
- 浏览器访问
http://localhost/index.html,即可看到渲染好的用户数据表格
内容的提问来源于stack exchange,提问作者Francheska
相关产品推荐
相关产品推荐

