如何实现Pug下拉框选书后在另一个Pug页面展示图书信息表格
问题解决:表单提交后无法传递图书ID并展示详情
核心问题分析
- 前端表单的
<select>未设置name属性,导致POST提交时不会携带选中的ID值 - 后端未配置表单解析中间件,无法读取POST请求的表单数据
- 后端错误地从
req.params获取数据,实际POST表单数据存储在req.body中 - 缺少根据ID查找对应图书详情的逻辑
具体修改步骤
1. 前端表单修改(forms.pug)
给select添加name属性,确保表单提交时携带选中的ID参数:
include Header.html head title Books script(type='text/javascript'). function checkIt(){ const select = document.getElementById('name'); alert(select.value); } body h2 #{lib} p #{desc} h3 Select a book br div(class="col-sm-12") div.form-group(class="sel") form(action ="/showBook" method="POST") // 新增name属性,参数名设为bookId select(type='text', id='name', name='bookId') for bk in bks option(value = bk.id) #{bk.title} button.btn.btn-primary(onclick=`checkIt()`) Submit it br p by me
2. 后端代码修改(Main.js)
添加表单解析中间件,从req.body获取ID并查找对应图书:
let express = require('express'); let app = express(); app.set('view engine', 'pug'); app.use(express.static(__dirname +'/public')); // 添加表单解析中间件,处理url编码的表单数据 app.use(express.urlencoded({ extended: true })); const inD = require("./input/books.json"); let books = inD.books; app.get("/forms", function( req, res){ res.render( 'Forms',{ lib : inD.library, desc : inD.description, bks : books }) }); app.post("/showBook", function( req, res){ // 从req.body获取表单提交的bookId const bookId = parseInt(req.body.bookId); // 根据ID查找对应的图书 const selectedBook = books.find(book => book.id === bookId); // 渲染页面时传入完整的图书数据 res.render( 'FormsBooks',{ book: selectedBook }); console.log(`Selected book ID: ${bookId}`); });
3. 详情页模板修改(formsBooks.pug)
使用传递的book对象展示完整图书信息:
include Header.html head title Form Tester body h2 Book Details for id:#{book.id} div.col-sm-6 table.table tr th ID td #{book.id} tr th Title td #{book.title} tr th Author td #{book.author} tr th Year td #{book.year} tr th Editions td #{book.editions} tr th Price td #{book.price} tr td colspan="2" button(class='btn btn-primary' type='button' onClick=`location.href='/formsBooks/delete/${book.id}'`) Delete button.btn.btn-primary(type="button", name="asdf" onclick="location.href='/forms'" value='back') Back to form
关键说明
- select必须设置
name属性,否则表单不会提交该字段的值 express.urlencoded()是解析POST表单数据的必要配置- 使用
Array.find()根据ID快速定位图书,确保传递完整数据给模板 - 详情页直接通过
book对象的属性展示信息,保证数据对应准确
内容的提问来源于stack exchange,提问作者xkellss
相关产品推荐
相关产品推荐

