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

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

问题描述

我有一个非常大的对象,我需要将它传递给客户端脚本中的一个函数.我曾尝试使用 JSON.stringify,但在使用这种方法时遇到了一些问题 - 主要与性能有关.有没有可能在 ejs 中做这样的事情?

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>

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

推荐答案

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

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天全站免登陆