How To Pass A Javascript Object That Contains Strings With Quotes From Node.js To The Browser?
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 html: Node.js/ex
Solution 1:
In your template, remove the JSON.parse.
var myObjectInBrowser = {{{myObjectString}}};
If you've already encoded the data as JSON, this is directly parseable by the JavaScript engine. If you add another JSON.parse to that, you are double-parsing.
Solution 2:
Quoting my own answer:
I
JSON.stringify()
any objects that my client scripts need and insert it as HTML5data-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<html><bodydata-locations='{"id":"1234","LL":{"lat":42.1,"lng":80.8}}'><script>var docs = JSON.parse($('body').attr('data-locations')); console.log(docs[0].LL); </script></body></html>
Post a Comment for "How To Pass A Javascript Object That Contains Strings With Quotes From Node.js To The Browser?"