ExpressJS 将变量传递给 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9268951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ExpressJS Pass variables to JavaScript
提问by Nick White
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.
我对此完全迷失了;我正在使用 NodeJS 来获取 JSON,我需要将变量传递到我的页面并让 JavaScript 使用数据。
app.get('/test', function(req, res) {
res.render('testPage', {
myVar: 'My Data'
});
That is my Express code (very simple for testing purposes); now using JADE I want to gather this data which I know to render on the page is simply
那是我的 Express 代码(对于测试来说非常简单);现在使用 JADE 我想收集这些我知道要在页面上呈现的数据很简单
p= myVar
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
但是我需要能够在 JavaScript 中收集这些数据(如果可能在 .js 文件中)但现在只是为了在我尝试过的警报框中显示变量
alert(#{myVar})
And many others if anyone can help be much appreciated
以及其他许多人,如果有人可以提供帮助,将不胜感激
采纳答案by dzajdband
Try the following:
请尝试以下操作:
alert('!{myVar}')
It's a good idea to JSON encode the data if is more than just a string.
如果数据不仅仅是字符串,则对数据进行 JSON 编码是个好主意。
alert('!{JSON.stringify(myVar)}')
回答by Bennit
As Timothy said:
正如提摩太所说:
<script type="text/javascript>var myVar = #{JSON.stringify(myVar)};</script>
This can also be done as follows in if you don't like to write HTML in jade templates:
如果您不喜欢在 jade 模板中编写 HTML,也可以按如下方式完成:
script
var myVar = !{JSON.stringify(myVar)};
var myVar2 = !{JSON.stringify(myVar2)};
Update: For Express 4 use script.
instead of script
so that it will be rendered as javascript instead of html.
更新:对于 Express 4 使用script.
而不是script
这样,它将被呈现为 javascript 而不是 html。
回答by Timothy Meade
Well, Javascript (and V8) has a built in function to render JSON from a object, and JSON happens to be syntactially compatible with Javascript.
好吧,Javascript(和 V8)有一个内置函数来从对象渲染 JSON,而且 JSON 恰好在语法上与 Javascript 兼容。
So the easiest way to do what your trying to do would be:
因此,做您想做的事情的最简单方法是:
<script type="text/javascript>var myVar = #{JSON.stringify(myVar)};</script>
And, yes, you can use HTML in a Jade template.
而且,是的,您可以在 Jade 模板中使用 HTML。
回答by BFree
I know I'm a bit late to the party, but I actually wrote a module (JShare) a few months ago to solve this exact problem. Check it out: https://npmjs.org/package/jshare
我知道我参加聚会有点晚了,但实际上我几个月前写了一个模块 (JShare) 来解决这个确切的问题。看看:https: //npmjs.org/package/jshare
回答by JP Richardson
You could leverage Now.js for this. It easily allows you to share variables client/server side real-time.
您可以为此利用 Now.js。它允许您轻松地实时共享客户端/服务器端的变量。
Check it out: http://www.nowjs.com/
看看:http: //www.nowjs.com/