我有一个与mongodb集成的nodejs项目。在这里,我创建了一个玉文件,其中有一个从数据库中获取的学生列表。针对每个学生记录,有一个编辑按钮。因此,当用户点击编辑按钮时,它需要将用户重定向到另一个玉(editstudent.jade
)文件,该文件将显示用户可以编辑该学生记录的表单。
为了实现这一目标,我在studentList.jade
文件中创建了下表。
studentList.jade
extends layout
block content
h1.
Student List
table
tr
th.
Name
th.
Age
th.
Contact
th.
Edit Student
th.
Delete Student
each student, i in studentlist
tr
td(id='studentname') #{student.name}
td #{student.age}
td
a(href="mailto:#{student.email}")=student.email
td
button(onclick='editstudent("#{student.name}")')= "Edit"
td
button(onclick='removestudent()')= "Remove"
script.
function editstudent(gh) {
alert("Edit "+gh+"'s Profile");
window.location.href = '/editstudent?gh=' + gh;
}
输出
当点击编辑按钮时,它会将名称作为参数&最初会弹出如下警告。
弹出提醒
我想将此名称显示为我从index.js调用的editstudent
页面的标题
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET student welcome page. */
router.get('/studentIndex', function(req, res, next) {
res.render('studentIndex', { title: 'Student Portal' });
});
/*GET the studentList page */
router.get('/studentList', function(req, res) {
var db = req.db;
var collection = db.get('studentcollection');
collection.find({},{},function(e,docs){
res.render ('studentList', {
"studentlist" : docs});
});
});
/* GET the editStudent page */
router.get('/editstudent', function(req, res) {
res.render('editstudent', { title : gh});
});
module.exports = router;
但我目前收到错误提及
gh未定义
editstudent.jade
extends layout
block content
h1 = title
p Welcome editor
button(onclick = 'backToList()')="Back"
script.
function backToList() {
window.location.href = '/studentList'
}
有关如何将此变量传递到重定向页面(editstudent.jade
)的任何建议,我们将不胜感激。
答案 0 :(得分:2)
您应该从请求路径中阅读gh
,因为您是在路径中发送的:/editstudent?gh=' + gh
router.get('/editstudent', function(req, res) {
let gh = req.query.gh;
res.render('editstudent', { title : gh});
});
答案 1 :(得分:1)
gh
。从查询参数
gh
/* GET the editStudent page */
router.get('/editstudent', function(req, res) {
res.render('editstudent', { title : req.query.gh});
});