How to pass a javascript object that contains strings with quotes from node.js to the browser?

前端 未结 2 733
野趣味
野趣味 2021-01-24 10:03

I have a node/express application and want to pass a javascript object to the browser. Currently I do this by JSON.stringifying the object and printing it into the

2条回答
  •  無奈伤痛
    2021-01-24 10:20

    Quoting my own answer:

    I JSON.stringify() any objects that my client scripts need and insert it as HTML5 data-whatever attributes. [then your client script can just read the dom attribute.]

    For example:

    //app.js
    app.get('/map', function(req, res){
      var data = {
        id: '1234',
        LL: {
          lat: 42.1,
          lng: 80.8,
      };
      res.locals.docsJSON = JSON.stringify([data]);
      res.render('locations/index');
    });
    
    //jade
    !!!
    html
      body(data-locations=locals.docsJSON)
      script
        var docs = JSON.parse($('body').attr('data-locations'));
        console.log(docs[0].LL);
    
    //html output
     
    
    
    

提交回复
热议问题