我是 Express Node 的新手,负责 Web 应用程序的前端。我需要能够让用户按下一个链接,并且对于该链接,当按下时将变量传递给index.js,此链接允许用户选择他们想要测试的问题类别。我不认为为每个类别设置不同的路线是最好的选择。但因为我是新人,所以我不知道该怎么做。
这是我在jade中链接的代码(我想在此处添加一些内容来执行我想要的操作),本文底部有一个指向页面屏幕截图的链接。
li.active
a(href='freeplay')
i.fa.fa-edit
span.nav-label Freeplay
span.fa.arrow
ul.nav.nav-second-level
li
a(href='freeplay/category') Category1
li
a(href='freeplay/category') Category2
li
a(href='freeplay/category') Category3
li
a(href='freeplay/category') Category4
li
a(href='freeplay/category') Category5
这是我处理它的index.js。 temp 是我想要保存类别字符串的变量。
//Handle the free play request
router.get('/freeplay' , isAuthenticated, freeplay.startFreePlay);
//Handle the free play request with category
router.get('/freeplay/category' , isAuthenticated, freeplay.startCategoryPlay);
最后,我希望能够将变量读取到 temp 中的 node.js 是我想要将用户选择的类别分配给的变量。
exports.startFreePlay = function(req, res) {
//grab a question that the user has not gotten right
//Get the users logged in id
userId = req.session.passport.user;
freePlayLogic.getQuestion(userId, function(question){
res.render("FreePlayQuestion", { question: question , questionID : question._id.toString()});
})
//Pass the question to render
};
exports.startCategoryPlay = function(req, res){
//grab a question that the user has not gotten right
//Get the users logged in id
userId = req.session.passport.user;
/**
* get a question from category "temp"
*/
freePlayLogic.getQuestionFromCategory(userId, "temp", function(question){
res.render("FreePlayQuestion", { question: question , questionID : question._id.toString()});
})
}
预先感谢您的帮助!
here is a screenshot of the web app with the category choices
最佳答案
所以看起来您正在尝试做的是让一个按钮将数据发送回您的服务器。执行此操作需要向服务器发出另一个请求。您可以添加一条路线来处理这些数据,如下所示...
app.get('/question/:id', function(req, res) {
var id = req.params.id;
//do something with this id like render a page
);
然后你的链接就会像这样
a(href="/question/1") Question 1
a(href="/question/2") Question 2
这应该可行,如果您有任何疑问,请发表评论:)
尝试添加此测试路由
app.get('/test/id', function(req, res) {
res.send(req.params.id);
);
关于javascript - 如何在jade中创建一个变量以在node.js中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34217396/