Pass variable from Express to Client JavaScript

让人想犯罪 __ 提交于 2019-12-14 02:35:47

问题


Ultimately I'm trying to pass JSON data from the Node server to be used by D3 in the client.

Here's my index.js

var express = require('express');
var router = express.Router();

var portmix = require('../data/holdings.json');

/* GET individual portfolio page. */
router.get('/portfolio/:portcode', function(req, res) {

  var porthold = [];
  for(var i in portmix){
    if(portmix[i].PortfolioBaseCode === req.params.portcode){
        porthold.push(portmix[i])
  }}

  res.render('index', { 
    pagetype: 'single_portfolio',
    holdings: porthold[0]
  });
});

module.exports = router;

Here's the ejs file:

<div class="portfolio">

    <h2><%= holdings.ReportHeading1 %></h2>
    <ul>
        <li>Cash: <%= holdings.CashMV %></li>
        <li>Fixed Income: <%= holdings.FixedMV %></li>
        <li>Equity: <%= holdings.EquityMV %></li>
        <li>Alternatives: <%= holdings.AltMV %></li>
    </ul>

    <div class="chart">
    </div>
</div> 

It works to display the "holdings" values. However, if I try to call it from a client side js using:

console.log("Holdings: " + holdings);

The result is

Holdings: undefined

Is there a way to do this? Or am I going about it all wrong?


回答1:


You can't call the EJS variables from the clientside, you have to output the JSON to the page, and then fetch it

<script type="text/javascript">

   var json_data = <%- JSON.stringify( holdings ); %>

   // use the above variable in D3

</script>

<div class="portfolio">

    <h2><%= holdings.ReportHeading1 %></h2>
    <ul>
        <li>Cash: <%= holdings.CashMV %></li>
        <li>Fixed Income: <%= holdings.FixedMV %></li>
        <li>Equity: <%= holdings.EquityMV %></li>
        <li>Alternatives: <%= holdings.AltMV %></li>
    </ul>

    <div class="chart">
    </div>
</div> 


来源:https://stackoverflow.com/questions/27787204/pass-variable-from-express-to-client-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!