EJS access express variable in JS onload function

帅比萌擦擦* 提交于 2019-12-06 06:59:50

问题


I know you can get the value of variables in an ejs file like so,

<h1><%= title %></h1>

if i were to use the same title variable in a onload javascript function in the same ejs page, how would i use it . for instance

<script>
window.onload(){
var s = <%= title %>
alert(s);
}
</script>

this function produces a console error saying

Uncaught syntax error: Unexpected identifier

although I'm able to see the actual value of the variable


回答1:


To output it within a script, the result will need to be understood as code.

Since you didn't note the value of title, I'll assume for the examples:

res.render('view', { title: 'My Site' });

When you use var s = <%= title %>, this results in creating the statement as:

var s = My Site

In this, My and Site are interpreted as individual variables separated only by an unexpected space. The engine is confused when it reaches Site without an operator between them, thus the Unexpected identifier you're getting.


It needs to instead create the statement:

var s = "My Site"

So the client script can also understand it as a string value.

One trick to accomplishing this is using JSON.stringify(). Since JSON took its syntax from JavaScript's expressions and literals, a JavaScript engine is capable of making sense of the result in many contexts (though, with its own take on strings, objects, etc.):

var s = <%- JSON.stringify(title) %>

Note, though, the switch to using <%- %> vs. <%= %>. This will disable HTML encoding, which is unnecessary and can lead to odd results inside of a <script>.




回答2:


I think you should try: html:

<h1 id="title"><%= title %></h1>

Js:

  <script>
    window.onload(){
    var s = document.getElementById("title").innerText;
    alert(s);
    }
  </script>


来源:https://stackoverflow.com/questions/33836533/ejs-access-express-variable-in-js-onload-function

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