问题描述
我在服务器上有一个非常重的查询,导致新的页面呈现,并且我想将查询的一些结果传递给客户端(作为一组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 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>
这篇关于传递对象到节点+ express + jade中的客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!