node.js 在 node + express + jade 中将对象传递给客户端?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7681821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing objects to client in node + express + jade?
提问by killermonkeys
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.
我在服务器上有一个非常重要的查询,它会导致新页面呈现,我想将查询的一些结果传递给客户端(作为对象的 javascript 数组)。这基本上是这样我以后不必做单独的 JSON 查询来获得相同的内容(大部分是静态的)。这些数据最终会很有用,但最初不是,所以我没有直接将其放入文档中。
app.get('/expensiveCall', function(req, res) {
// do expensive call
var data = veryExpensiveFunction();
res.render('expensiveCall.jade', {
locals: {
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
data 是一个对象数组,最初只使用一些对象。我想传递整个数据或一些子集(取决于情况)。我的玉看起来像普通的玉,但我想包括类似的东西
<script type="text/javascript">
var data = #{data};
</script>
but this doesn't work (it's an array of objects).
但这不起作用(它是一个对象数组)。
回答by Adrien
You can't inline a JS object like that, but you can JSON.stringifyit before:
你不能像那样内联一个 JS 对象,但你可以JSON.stringify在之前:
<script type="text/javascript">
var data = !{JSON.stringify(data)};
</script>

