上一篇
html选中表格一行数据库中
- 行业动态
- 2025-04-29
- 3496
通过JavaScript监听表格行点击事件获取数据,利用AJAX将选中行数据发送至后端API,后端解析后执行
选中表格行并获取数据
<table id="dataTable" border="1"> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> </tr> <tr> <td>1</td> <td>张三</td> <td>25</td> </tr> <tr> <td>2</td> <td>李四</td> <td>30</td> </tr> </table> <script> document.querySelectorAll('#dataTable tr').forEach(row => { row.addEventListener('click', function() { // 排除表头 if(this.cells[0].innerText !== '') { const rowData = { id: this.cells[0].innerText, name: this.cells[1].innerText, age: this.cells[2].innerText }; // 触发数据提交 submitRowData(rowData); } }); }); function submitRowData(data) { fetch('/api/saveRow', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) }) .then(response => response.json()) .then(result => alert(result.message)) .catch(error => console.error('Error:', error)); } </script>
后端处理:接收数据并存入数据库(以PHP为例)
<?php // 连接数据库 $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'password'); // 获取POST数据 $data = json_decode(file_get_contents('php://input'), true); // 准备SQL语句(防止SQL注入) $stmt = $pdo->prepare("INSERT INTO users (id, name, age) VALUES (:id, :name, :age)"); $stmt->bindParam(':id', $data['id']); $stmt->bindParam(':name', $data['name']); $stmt->bindParam(':age', $data['age']); // 执行并返回结果 if($stmt->execute()) { echo json_encode(['message' => '数据保存成功']); } else { echo json_encode(['message' => '保存失败']); } ?>
数据库表结构示例
字段名 | 类型 | 说明 |
---|---|---|
id | INT(11) | 主键自增 |
name | VARCHAR(50) | 用户姓名 |
age | INT(11) | 用户年龄 |
相关问题与解答
问题1:如何实现多选表格行并批量保存到数据库?
解答:
- 修改前端代码,允许
Ctrl
或Shift
多选行,将选中数据存储在数组中 - 调整后端接口,接收数组格式数据并循环插入数据库
- 示例代码修改:
let selectedRows = []; // 存储多选数据 // 修改点击事件逻辑,支持多选 // 后端改为遍历$_POST['data']数组批量插入
问题2:如何实现选中行后直接更新数据库记录?
解答:
- 在表格中增加”编辑”按钮而非直接选中
- 点击编辑时弹出表单修改数据
- 提交时使用
UPDATE
语句而非INSERT
- 关键代码修改:
-将INSERT改为UPDATE $stmt = $pdo->prepare("UPDATE users SET name=:name, age=:age WHERE id=: