刚刚在学ejs+express,正在做一个小网页。过程是这样的:
1、testA.ejs通过nodejs获取到数据库中文章的title、time、id并在网页上显示;
2、testA.ejs将文章id传给testB.ejs,testB.ejs获得文章id;
3、testB.ejs根据id来和数据库查询到对应id的文章,并显示到网页。
现在我遇到了两个问题:
1、ejs页间如何传参?
试了传统的通过href=testA.ejs?aid=来传参,但提示404.
2、在ejs模板中,怎么才能完成根据用户在文章列表中选择的文章跳转到显示对应文章详情的页面?
我能完成nodejs->js->ejs的查询数据库和存入数据库的过程,但不知如何处理多个页面的交互。因为是刚开始学,很多方面都很模糊,问的问题也小白,希望有朋友能帮我解解疑惑。非常感谢!
迷茫2017-04-17 11:41:00
Additional note~
According to your needs:
You can write like this
get ==> /u/id
Receive it like this in express
app.get('/u/:id',function(req,res){
var id = req.params.id;
//操作数据库方法...
res.render('index',{
//页面传值...
});
});
can also be written like this:
get ==>/u?id=xxx
Receive it like this in express
app.get('/u',function(req,res){
var id = req.query.id;
//操作数据库方法...
res.render('index',{
//页面传值...
});
});
PHPz2017-04-17 11:41:00
If you want to jump, you need routing. Now suppose you need this effect/posts ==>查询数据库,拿到全部文章posts ==> 渲染到testA.ejs(单一条的链接为/post?id=XXX)
For single details: /post?id=XX ==>查询数据库,拿到对应id文章post ==> 渲染到testB.ejs
A little bit of code
app.get("/posts",function(req,res){
//查询文章
fetchPosts(function(err,posts){
res.render("testA.ejs",{posts:posts})//渲染到模板
})
})
app.get("/post",function(req,res){
var id = req.query.id
//查询文章
fetchPost(id, function(err,post){
res.render("testB.ejs",{post:post})//渲染到模板
})
})
The above is just a simple pseudo-code to help you understand the process. If you have any questions, you can leave a message. In addition, there are a lot of examples of this problem on the Internet. It is recommended to check them out