3

I'm having a little bit problems, I'm trying to send an object to use on my Javascript client side, whenever I render the view. I am sending it this way (Im using Handlebars)

  > locations=[ {
    >               local:"my_local",                    
    >                desc:"myDesc"                  
    >               }]; 

res.render('myView', { locaciones:locaciones });

// Then in my view Inside a script tag i try to get that var and print it

<script>
  var myObj='{{locations}}';
   console.log(locations);
</script>

the result is this :

[object]

and I can't use any property of it because it's undefined

2
  • Try console.log(locations.local); Commented Dec 8, 2015 at 6:11
  • @s007 the result is "undefined" Commented Dec 8, 2015 at 6:17

2 Answers 2

7

You can send your object as a string.

Like locations = JSON.stringify({local:"my_local",desc:"myDesc"});

And on client side you can parse it to get an Object

Like loc = JSON.parse(locations);

Now you can use loc as Object.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting this error when i try to parse " SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data "
the problem was that JSON.stringify changed the quotes for &quote so I couldn't parse it on the client side. I fixed it with this : loc=JSON.parse(locations.replace(/&quot;/g,'"'))
0

I know this is an old post but in case others are looking for an easy way to pass an object from the server to the client in nodejs here's how I do it.

On the server I do something like:

res.render('my_page',{'my_object': my_object});

Then on the client side in my jade I'd do:

-var name = my_object.name;

(assuming there's a "name" property in my_object)

Then just use it however you need it.

Like:

p Hello #{name}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.