0

In node.js i am sending the values to html through

render('/abc', mydata)

"mydata" contains json_encoded format.

And i am reading this as :

{{=mydata}}

Now, in the same html page i have javascript like :

 <script>
 xyz(); 
  function xyz() { 
      // i need to read the "mydata" here.
  }
 </script>

I tried this which didn't work xyz({{=mydata}}) , How can i use that dynamic data in node.js ??

6
  • Which view engine is this using? And, what is the result of xyz({{=mydata}}) as seen by the browser? Commented Sep 18, 2013 at 9:05
  • m using express framework. And when i add that xyz({{=mydata}}) i can see an object being printed when i inspect element. But my JS fails to work Commented Sep 18, 2013 at 9:12
  • What is the value for app.set('view engine', ???)? Express isn't a view engine itself and the answer will likely vary based on which you're using with Express. Commented Sep 18, 2013 at 9:14
  • can u please tell me, where this would be set ?? Commented Sep 18, 2013 at 9:17
  • I am unsure on where that is set !!. Can u please tell me where i can find that ? Commented Sep 18, 2013 at 9:25

1 Answer 1

1

A few possibilities:

  • mydata may not actually be a local in the view.

    Express can't pass along the name of the variable used as the argument. Only the properties of the Object it references.

    So, you may need to create a new Object around mydata to name a property for it:

    render('/abc', { mydata: mydata });
    
  • The output may be HTML-encoded by {{= }}, which will likely cause SyntaxErrors in JavaScript.

    So, the response may contain something like:

    xyz({&quot;foo&quot;:&quot;bar&quot;})
    

    Rather than:

    xyz({"foo":"bar"})
    

    How to go about skipping HTML-encoding will depend on which view engine you're using with Express. But, it may be as simple as replacing the = with a -:

    xyz({{-mydata}})
    
  • mydata may still be an Object rather than the String of json_encoded data it seems you were expecting.

    If that's the case, it may be using the standard .toString(), which will produce:

    xyz([object Object])
    

    And, you may still need to stringify() mydata.

    xyz({{-JSON.stringify(mydata)}})
    
Sign up to request clarification or add additional context in comments.

2 Comments

When i inspect element, i can see it as [Object object] on this xyz({{=mydata}}
Hey, its working but with a slight change xyz({{=JSON.stringify(mydata)}}). Thank you very much

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.