在 node + express + jade 中将对象传递给客户端? [英] Passing objects to client in node + express + jade?

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

问题描述

我在服务器上有一个非常重要的查询,它导致新的页面呈现,我想将查询的一些结果传递给客户端(作为对象的 javascript 数组).这基本上是这样我以后不必做单独的 JSON 查询来获得相同的内容(大部分是静态的).这些数据最终会很有用,但最初不是,所以我没有直接将其放入文档中.

I have a pretty heavyweight query on the server that results in a new page render, and I'd like to pass along some of the results of the query to the client (as a javascript array of objects). This is basically so I don't have to do a separate JSON query later to get the same content (which is mostly static). The data will be useful eventually, but not initially so I didn't put it directly into the document.

app.get('/expensiveCall', function(req, res) {
    // do expensive call
    var data = veryExpensiveFunction();
    res.render('expensiveCall.jade', {
        locals: {
                data: data,
                }
        });
    });
});

data 是一个对象数组,最初只使用了一些.我想传递整个数据或一些子集(取决于情况).我的玉看起来像普通的玉,但我想包括像

data is a array of objects and only some are initially used. I'd like to pass either the entirety of data over or some subsets (depending on the situation). My jade looks like normal jade, but I would like to include something like

<script type="text/javascript">
var data = #{data};
</script>

但这不起作用(它是一个对象数组).

but this doesn't work (it's an array of objects).

推荐答案

你不能像那样内联一个 JS 对象,但你可以在它之前JSON.stringify:

You can't inline a JS object like that, but you can JSON.stringify it before:

<script type="text/javascript">
  var data = !{JSON.stringify(data)};
</script>

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

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