Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

json - Passing objects to client in node + express + jade?

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).

question from:https://stackoverflow.com/questions/7681821/passing-objects-to-client-in-node-express-jade

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...