EJS access express variable in JS onload function

时光怂恿深爱的人放手 提交于 2019-12-04 11:50:11

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

I think you should try: html:

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

Js:

  <script>
    window.onload(){
    var s = document.getElementById("title").innerText;
    alert(s);
    }
  </script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!