问题
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