Express/Node.js-带有数据的渲染页面 [英] Express / Node.js - Render page with data
问题描述
我有一个Teams
列表显示为页面上的链接列表,此刻,我有一个文本框....单击该Team
的链接时,该链接的Key
提取Team
并将其发送到/team/:key
路由,它按Key
搜索Team
,获取数据并将其发送回去.如果数据已成功发送回JS文件,则Team
名称将输出到文本框.
I have a list of Teams
displayed as a list of links on my page, at the moment, I have a textbox....when the link for that Team
is clicked, the Key
for that Team
is taken and sent to the /team/:key
route, it searches for the Team
by Key
, gets the data and sends the data back. If the data was successfully sent back to the JS file then the Team
name is output to the textbox.
当单击链接并使用Team.findByKey
检索数据时,我想更改此设置,我想呈现一个新页面('teamDetails')并将该Team
的数据传递给它.这样,我就可以做到Team
的每个链接都链接到Team's
单个页面,并在其上提供完整的详细信息.
I want to change this, when the link is clicked and the data has been retrieved using Team.findByKey
I want to render a new page ('teamDetails') and pass it the data for that Team
. This way I can make it so that each link for a Team
links to the Team's
individual page with their full details on it.
有什么主意我会如何适应这条/team/:key
路线来做到这一点?
Any idea how I would adapt this /team/:key
route to do this?
JS file
// Setup teamsLink to retrieve Team info for whichever Team was clicked
Team.initTeamsLink = function(){
$("a.teamLink").live("click", function(e){
e.preventDefault();
var teamId = ($(this)[0]).getAttribute('id');
$.get('/team/'+teamId, function(response){
if(response.retStatus === 'success'){
var teamData = response.teamData;
$('#teamId').val(teamData.key);
$('#teamName').val(teamData.name);
} else if(response.retStatus === 'failure'){
}
});
});
};
Route
app.get('/team/:key', function(req, res) {
util.log('Serving request for url [GET] ' + req.route.path);
Team.findByKey(req.params.key, function(err, teamData){
if(!err && teamData){
teamData = teamData;
res.json({
'retStatus' : 'success',
'teamData' : teamData
});
} else {
util.log('Error in fetching Team by key : ' + req.params.key);
res.json({
'retStatus' : 'failure',
'msg' : 'Error in fetching Team by key ' + req.params.key
});
}
});
});
推荐答案
而不是res.json()
,您可以使用模板引擎来呈现单个团队的页面.假设您要使用 EJS 模板:
Instead of res.json()
, you could use a templating engine which would render the individual team's page. Say you want to use EJS templates:
npm install ejs
接下来,创建views/team.ejs
,其中将包含团队的EJS模板.在您的路由中,将res.json()
替换为对模板引擎的调用:
Next, create views/team.ejs
, which would contain the EJS template for the team. In your route, replace res.json()
with a call to the templating engine:
res.render('team.ejs', { 'teamData' : teamData });
编辑:只需阅读您有关使用Jade模板的评论:代码非常相似,只需将team.ejs
替换为teamDetails.jade
.
EDIT: just read your comment about using Jade templates: the code is very similar, just replace team.ejs
with teamDetails.jade
.
此外,由于您不想再执行AJAX请求,您可能可以删除处理链接上的点击事件的客户端代码.
Also, you probably can remove your client-side code which handles click events on the links, since you don't want to perform an AJAX request anymore.
这篇关于Express/Node.js-带有数据的渲染页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!