简体   繁体   English

EJS在JS onload函数中访问express变量

[英]EJS access express variable in JS onload function

I know you can get the value of variables in an ejs file like so,我知道你可以像这样在 ejs 文件中获取变量的值,

<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 .如果我要在同一个 ejs 页面的 onload javascript 函数中使用相同的标题变量,我将如何使用它。 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虽然我能够看到变量的实际值

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:由于您没有注意到title的值,我将假设以下示例:

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

When you use var s = <%= title %> , this results in creating the statement as:当您使用var s = <%= title %> ,这会导致将语句创建为:

var s = My Site

In this, My and Site are interpreted as individual variables separated only by an unexpected space.在这种情况下, MySite被解释为仅由意外空格分隔的单个变量。 The engine is confused when it reaches Site without an operator between them, thus the Unexpected identifier you're getting.当引擎在它们之间没有操作员的情况下到达Site时,引擎会感到困惑,因此您会得到Unexpected identifier


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() .实现这一点的一个技巧是使用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.):由于 JSON 的语法来自 JavaScript 的表达式和文字,因此 JavaScript 引擎能够在许多上下文中理解结果(尽管,它自己处理字符串、对象等):

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> .这将禁用 HTML 编码,这是不必要的,并且会导致<script>内部出现奇怪的结果。

I think you should try: html:我认为你应该尝试: html:

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

Js: JS:

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

When you have当你有

var s = <%= title %>

This parses it like it would for HTML, so there are no quotes.这会像解析 HTML 一样解析它,因此没有引号。 For example, if the title was "My Page", your javascript would be:例如,如果标题是“我的页面”,则您的 javascript 将是:

var s = My Page

Since there are no quotes around My Page, this gives a JavaScript error.由于我的页面周围没有引号,这会导致 JavaScript 错误。 You could use JSON.parse , or just put quotes around it to fix this:你可以使用JSON.parse ,或者只是在它周围加上引号来解决这个问题:

var s = "<%= title %>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM