在 ExpressJS 中将变量传递给 JavaScript [英] Pass variables to JavaScript in ExpressJS
问题描述
我对此完全迷失了;我正在使用 NodeJS 来获取 JSON,我需要将变量传递到我的页面并让 JavaScript 使用数据.
I am completely lost on this; I am using NodeJS to fetch a JSON and I need to pass the variable to my page and have JavaScript use the data.
app.get('/test', function(req, res) {
res.render('testPage', {
myVar: 'My Data'
});
那是我的 Express 代码(对于测试来说非常简单);现在使用 EJS 我想收集这些我知道要在页面上呈现的数据很简单
That is my Express code (very simple for testing purposes); now using EJS I want to gather this data which I know to render on the page is simply
<%= myVar %>
但我需要能够在 JavaScript 中收集这些数据(如果可能在 .js 文件中)但现在只是在我尝试过的警报框中显示变量
But I need to be able to gather this data in JavaScript (if possible within a .js file) but for now just to display the variable in an Alert box I have tried
在 Jade 中,它就像 alert('!{myVar}')
或 !{JSON.stringify(myVar)}
.我可以在 EJS 中做类似的事情吗?我不需要像 <input type=hidden>
这样的任何字段并在 javascript 中获取该字段的值.如果有人可以提供帮助,不胜感激
In Jade it is like alert('!{myVar}')
or !{JSON.stringify(myVar)}
. Can I do something similar in EJS. I don't need any field like <input type=hidden>
and taking the value of the field in javascript. If anyone can help be much appreciated
推荐答案
你可以使用这个(客户端):
You could use this (client-side):
<script>
var myVar = <%- JSON.stringify(myVar) %>;
</script>
你也可以让 EJS 渲染一个 .js
文件:
You could also get EJS to render a .js
file:
app.get('/test.js', function(req, res) {
res.set('Content-Type', 'application/javascript');
res.render('testPage', { myVar : ... });
});
但是,模板文件 (testPage
) 仍然需要具有 .html
扩展名,否则 EJS 将找不到它(除非您另外告诉 Express).
However, the template file (testPage
) would still need to have the .html
extension, otherwise EJS won't find it (unless you tell Express otherwise).
正如@ksloan 在评论中指出的那样:您必须小心 myVar
包含的内容.如果它包含用户生成的内容,这可能会使您的网站容易受到脚本注入攻击.
As @ksloan points out in the comments: you do have to be careful what myVar
contains. If it contains user-generated content, this may leave your site open for script injection attacks.
防止这种情况发生的可能解决方案:
A possible solution to prevent this from happening:
<script>
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
var myVar = JSON.parse(htmlDecode("<%= JSON.stringify(myVar) %>"));
</script>
这篇关于在 ExpressJS 中将变量传递给 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!