javascript Express / Node.js - 用数据渲染页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15270922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:07:35  来源:igfitidea点击:

Express / Node.js - Render page with data

javascriptnode.jsexpress

提问by germainelol

I have a list of Teamsdisplayed as a list of links on my page, at the moment, I have a textbox....when the link for that Teamis clicked, the Keyfor that Teamis taken and sent to the /team/:keyroute, it searches for the Teamby Key, gets the data and sends the data back. If the data was successfully sent back to the JS file then the Teamname is output to the textbox.

我有一个列表Teams作为我的网页上的链接列表显示,在那一刻,我有一个文本框....的链接,当Team点击时,Key对于Team被取出并送至/team/:key路线,它将搜索Teamby Key,获取数据并将数据发回。如果数据成功发送回 JS 文件,则Team名称将输出到文本框。

I want to change this, when the link is clicked and the data has been retrieved using Team.findByKeyI 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 Teamlinks to the Team'sindividual page with their full details on it.

我想改变这一点,当点击链接并使用Team.findByKey我想呈现一个新页面('teamDetails')检索数据并将数据传递给它时Team。通过这种方式,我可以使每个链接都指向单个页面的Team链接,其中Team's包含完整的详细信息。

Any idea how I would adapt this /team/:keyroute to do this?

知道我将如何调整这/team/:key条路线来做到这一点吗?

JS file

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

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
        });
      }
    });
  });

采纳答案by robertklep

Instead of res.json(), you could use a templating engine which would render the individual team's page. Say you want to use EJStemplates:

代替res.json(),您可以使用模板引擎来呈现单个团队的页面。假设您要使用EJS模板:

npm install ejs

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:

接下来, create views/team.ejs,它将包含团队的 EJS 模板。在您的路线中,替换res.json()为对模板引擎的调用:

res.render('team.ejs', { 'teamData' : teamData });

EDIT: just read your comment about using Jade templates: the code is very similar, just replace team.ejswith teamDetails.jade.

编辑:只需阅读您关于使用 Jade 模板的评论:代码非常相似,只需替换team.ejsteamDetails.jade.

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.

此外,您可能可以删除处理链接上单击事件的客户端代码,因为您不想再执行 AJAX 请求。

回答by MrPovod

Use handlebars templates - http://handlebarsjs.com/

使用把手模板 - http://handlebarsjs.com/

npm install handlebars
npm install hbs

Coffe-script:

咖啡脚本:

hbs = require 'hbs'

app.set 'views', __dirname + '/app/views' #folder with your views
app.set 'view engine', 'hbs'
app.use express.bodyParser()
app.use express.methodOverride()

In the router:

在路由器中:

res.render 'index', {title: 'index'} #view name and context