简体   繁体   中英

Dynamic values in javascript - Node.js

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 ??

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)}}) 

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