【问题标题】:How do I send rendered html AND data to the browser with node?如何使用节点将呈现的 html 和数据发送到浏览器?
【发布时间】:2017-03-21 21:35:39
【问题描述】:

在 index.html 中,我有一个带有 action="/results" 的搜索表单。服务器端我有这个代码:

app.get('/results', function(req, res) {
  api.getInfo({query: req.query.searchStr}).then(function(data) {
    res.render('results', {title: 'Search Results'}, function(err, html) {
      res.send(html);
    });
  });
});

如果我写res.send(data),那么这些数据就会变成一个字符串并在浏览器中吐出。所以我需要一种方法来发送呈现的 html,但还要将data 放入客户端 javascript。最传统的方法是什么?

【问题讨论】:

    标签: javascript html node.js web-development-server


    【解决方案1】:

    您可以将数据发送到您的模板:

     res.render('results', {title: 'Search Results', data: data });
    

    然后在你的模板文件中引用data

    // results.ejs
    var data = <%= data %>;
    // or
    doSomethingWithData(<%= data %>);
    

    【讨论】:

      猜你喜欢
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多