简体   繁体   中英

How to use node.js variable in a function on the client side?

I have a rather strange problem. On server side, I call an an ejs-page by

res.render('index', {varArray: JSON.parse(response)});

When I try to use the variable "varArray" within HTML-Code, everything works fine, eg:

<% for (var i = 0; i < varArray.length; i++) { %>
    <option value="<%= varArray[i].id %>"><%= varArray[i].name %></option>
<% } %>

BUT: As soon as I want to use the same variable in a function on the same page, I get an error message, that this variable is undefined.

<body>
<script>
function test() {
  for (var i = 0; i < varArray.length; i++) {
// do something
  }
};
</script>

I hope, someone can help me.

Unfortunately I can't test this in ejs, but if its a JavaScript Array you could...

  1. JSON.stringify() the variable,
  2. print string to the dom
  3. Assign it to a variable within the desired scope.

 <% for (var i = 0; i < varArray.length; i++) { %> <option value="<%= varArray[i].id %>"><%= varArray[i].name %></option> <% } %> <script> var varArray = <%= JSON.stringify(varArray) %>; function test() { for (var i = 0; i < varArray.length; i++) { // do something } }; </script>

If the test() function isn't rendered through ejs then you could assign it to the Global object (window) then use it anywhere after it's been defined...

 <% for (var i = 0; i < varArray.length; i++) { %> <option value="<%= varArray[i].id %>"><%= varArray[i].name %></option> <% } %> <script> window.varArray = <%= JSON.stringify(varArray) %>; </script> <script> function test() { for (var i = 0; i < varArray.length; i++) { // do something } }; </script>

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