问题描述
我知道你可以像这样在ejs文件中获取变量的值,
< h1><% = title%>< / h1>
如果我在同一个ejs页面的onload javascript函数中使用相同的title变量,我会用它吗?例如
< script>
window.onload(){
var s =<%= title%>
alert(s);
}
< / script>
此函数产生控制台错误
虽然我能够看到变量的实际值
要在脚本中输出,结果需要理解为代码。
由于你没有注意到 title
的价值,我将假设这些例子:
res.render('view',{title:'My Site'});
当您使用 var时s =<%= title%>
,这会导致将语句创建为:
var s =我的网站
在此,我的
和站点
被解释为仅由意外空格分隔的单个变量。当它到达站点
时引擎就会感到困惑,它们之间没有运算符,因此你得到的是意外的标识符
。 / p>
需要创建声明:
var s =我的网站
因此客户端脚本也可以理解它是一个字符串值。
实现此目的的一个技巧是使用。由于JSON从JavaScript的表达式和文字中获取了它的语法,因此JavaScript引擎能够在许多上下文中理解结果(尽管它有自己的字符串,对象等):
var s =<% - JSON.stringify(title)%>
但请注意,切换到使用<% - %>
与<%=%>
。这将禁用HTML编码,这是不必要的,并且可能导致< script>
内的奇怪结果。
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
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:
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>
.
这篇关于EJS在JS onload函数中访问express变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!