在node / express + ejs中将对象传递给客户端? [英] Passing an object to client in node/express + 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屋!