Accessing EJS variable in Javascript logic

此生再无相见时 提交于 2019-11-27 01:28:57

问题


I'm working on a Node.js app (it's a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the proper room.

Right now, it's being done like this with Express v2.5.8:

server.get("/room/:name/:roomId, function (req, res) {
  game = ~databaseLookup~
  res.render("board", { gameState : game.gameState });
}

Over in board.ejs I can access the gameState manner with code like this:

<% if (gameState) { %>
  <h2>I have a game state!</h2>
<% } %>

Is there a way for me to import this into my JavaScript logic? I want to be able to do something like var gs = ~import ejs gameState~ and then be able to do whatever I want with it--access its variables, print it out to console for verification. Eventually, what I want to do with this gameState is to display the board properly, and to do that I'll need to do things like access the positions of the pieces and then display them properly on the screen.

Thanks!


回答1:


You could directly inject the gameState variable into javascript on the page.

<% if (gameState) { %>
     <h2>I have a game state!</h2>
     <script>
        var clientGameState = <%= gameState %>            
     </script>
<% } %>

Another option might be to make an AJAX call back to the server once the page has already loaded, return the gameState JSON, and set clientGameState to the JSON response.

You may also be interested in this: How can I share code between Node.js and the browser?




回答2:


I feel that the below logic is better and it worked for me.

Assume the variable passed to the ejs page is uid, you can have the contents of the div tag or a h tag with the variable passed. You can access the contents of the div or h tag in the script and assign it to a variable.

code sample below : (in ejs)

<script type="text/javascript">
    $(document).ready(function() {
        var x = $("#uid").html(); 
        alert(x);  // now JS variable 'x' has the uid that's passed from the node backend.
    });
</script>

<h2 style="display:none;" id="uid"><%=uid %></h2>



回答3:


Well, in this case you can simply use input text to get data. It is easy and tested when you use it in firebase.

<input type="text" id="getID" style="display: none" value="<%=id%>">


来源:https://stackoverflow.com/questions/11289793/accessing-ejs-variable-in-javascript-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!