在node / express + ejs中将对象传递给客户端? [英] Passing an object to client in node/express + ejs?

查看:176
本文介绍了在node / express + ejs中将对象传递给客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的对象,我需要传递给客户端脚本中的一个功能。我已经尝试使用JSON.stringify,但是遇到这种方法的几个问题 - 主要是性能相关的。可以在ejs中做这样的事情吗?

  app.get('/ load',function(req,res) {
var data = {
layout:'interview / load',
localals:{
interview:'',
data:someLargeObj
}
};
res.render('load',data);
});

在我的客户端脚本中,我将这个对象传递给这样一个函数

 < script type =text / javascript> 
load(<% - data%>); // load是客户端脚本中的一个函数
< / script>

当我尝试这个我得到

 < script type =text / javascript> 
load();
< / script>

 < script type =text / javascript> 
load([Object object]);
< / script>


解决方案

这是预期的行为。您的模板引擎正在尝试从您的对象创建一个导致[Object对象]的字符串。如果你真的想传递这样的数据,我认为你通过字符串对象来做正确的事情。


I have a pretty large object that I need to pass to a function in a client script. I have tried using JSON.stringify, but have run into a few issues with this approach - mostly performance related. Is it possible to do something like this in ejs?

app.get('/load', function(req, res) {
    var data = {
        layout:'interview/load',
        locals: {
            interview: '',
            data: someLargeObj
        }
    };
    res.render('load', data);
});

And in my client script, I would pass this object to a function like so

<script type="text/javascript">
    load(<%- data %>); // load is a function in a client script
</script>

When I try this I get either

<script type="text/javascript">
    load();
</script>

or

<script type="text/javascript">
    load([Object object]);
</script>

解决方案

That is the expected behavior. Your template engine is trying to create a string from your object which leads to [Object object]. If you really want to pass data like that I think you did the correct thing by stringifying the object.

这篇关于在node / express + ejs中将对象传递给客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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