Node.js+Express环境下如何获取HTML表格点击按钮选中行的数据
问题根因
你当前的实现存在三个核心问题导致后端无法拿到数据:
- 你将整个表格套在同一个
<form>标签中,表单提交时默认只会提交<input>、<button>等表单元素的值,<td>标签上的name属性不属于表单字段,不会被自动提交。 - 你的EJS模板代码存在多余的闭合
</td>标签,会导致HTML结构解析异常。 - 若未配置Express内置的解析中间件,
req.body默认会是undefined。
解决方案
方案一:普通表单提交(页面会刷新)
第一步:修改EJS模板代码
将整表的大表单删除,改为每行单独绑定表单,同时用隐藏域存储当前行的订单字段:
<table id="order-history"> <thead> <tr> <th>Date of Order</th> <th>Order ID</th> <th>Order Total</th> <th>Order Status</th> <th>Tracking Info</th> <th>Order Details</th> </tr> </thead> <tbody> <% orders.forEach(function(order){ %> <tr> <form action="/user-orders" method="POST"> <!-- 隐藏域存储订单字段 --> <input type="hidden" name="date" value="<%= order.date %>"> <input type="hidden" name="id" value="<%= order.id %>"> <input type="hidden" name="cost" value="<%= order.cost.toFixed(2) %>"> <input type="hidden" name="status" value="<%= order.status %>"> <td><%= order.date%></td> <td><%= order.id%></td> <td>$<%= order.cost.toFixed(2) %></td> <td><%= order.status%></td> <td> <button type="submit" name="action" value="viewTracking" class="profile-edit-btn" style="color:#0062cc; background:rgb(29, 29, 29); width:100%">View</button> </td> <td> <button type="submit" name="action" value="viewOrder" class="profile-edit-btn" style="color:#0062cc; background:rgb(29, 29, 29); width:100%">View</button> </td> </form> </tr> <% }) %> </tbody> </table>
第二步:配置Express解析中间件
在路由定义前添加表单解析中间件:
// 解析表单提交的x-www-form-urlencoded格式数据 app.use(express.urlencoded({ extended: true }));
第三步:修改后端路由代码
直接从req.body读取字段即可:
app.post('/user-orders', function (req, res) { const orderData = { date: req.body.date, id: req.body.id, cost: '$' + req.body.cost, status: req.body.status, action: req.body.action // 区分是查看物流还是订单详情 } console.log(orderData); // 后续自行处理业务逻辑和返回 })
方案二:AJAX提交(页面无刷新)
如果不需要刷新页面,可以用前端JS获取当前行数据后异步提交:
第一步:前端添加交互代码
在页面底部添加JS代码:
// 给所有按钮绑定点击事件 document.querySelectorAll('.profile-edit-btn').forEach(btn => { btn.addEventListener('click', function(e) { e.preventDefault(); // 阻止默认提交行为 // 获取当前按钮所在的行 const currentRow = this.closest('tr'); // 组装订单数据 const orderData = { date: currentRow.children[0].textContent.trim(), id: currentRow.children[1].textContent.trim(), cost: currentRow.children[2].textContent.trim(), status: currentRow.children[3].textContent.trim(), action: this.name } // 发送异步请求 fetch('/user-orders', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderData) }).then(res => res.json()) .then(result => { // 处理后端返回结果 }) }) })
第二步:配置Express解析中间件
在路由定义前添加JSON解析中间件:
app.use(express.json());
第三步:后端路由代码和方案一一致,直接读取req.body即可。
内容的提问来源于stack exchange,提问作者bob_jones
相关产品推荐
相关产品推荐

