将变量从Express传递到客户端JavaScript [英] Pass variable from Express to Client JavaScript

查看:108
本文介绍了将变量从Express传递到客户端JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最终,我试图从Node服务器传递JSON数据,以供客户端中的D3使用.

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

这是我的index.js

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;

这是ejs文件:

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

它可以显示馆藏"值.但是,如果我尝试使用以下方法从客户端js调用它:

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

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

结果是

Holdings: undefined

有没有办法做到这一点?还是我要解决所有问题?

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

推荐答案

您不能从客户端调用EJS变量,必须将JSON输出到页面,然后再获取

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> 

这篇关于将变量从Express传递到客户端JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆