简体   繁体   中英

Jade / Expressjs: Pass objects from server to client

I'm trying to pass an object from my endpoint to Jade but It keeps giving me Uncaught SyntaxError: Unexpected identifier on Stat! Can someone help me please. Here is my code:

app.get('/stats', function (req, res, next) {

    var stats ={
        'm0t20': {a:0,b:0,c:0,d:0},
        'm20t30': {a:0,b:0,c:0,d:0},
    };
   res.render('chart',{'stat':stats});
 }

and in my jade and I cant get the value of stat:

 script(type='text/javascript').
        var stats= #{stat};

If you want to interpolate object from you express, the easiest and cleanest way is to serialize them. For the moment, once interpolated, you are trying to write something like this:

var stats = [Object object];

Which isn't a valid JavaScript syntax :/ So, on the server side, serialize your object:

 app.get(..., function (req, res) {
    var stats = { ... };
    res.render('chart', { stats: JSON.stringify(stats) });
 });

And, on the client side, just use the serialized object; You'll need to use ! instead of # to prevent jade from escaping characters like quotes.

script.
    var stats = !{stats};
    alert(stats.myProp);

Keep in mind that you are injecting direct JavaScript code into your page.
DO NOT do that if the serialized object could contain any user input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM