在客户端 JavaScript 中访问 Express.js 局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10919650/
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
Accessing Express.js local variables in client side JavaScript
提问by braitsch
Curious if I'm doing this right and if not how you guys would approach this.
很好奇我是否做对了,如果不是,你们会如何处理这个问题。
I have a Jade template that needs to render some data retrieved from a MongoDB database and I also need to have access to that data inside a client side JavaScript file.
我有一个 Jade 模板,需要呈现从 MongoDB 数据库中检索到的一些数据,我还需要访问客户端 JavaScript 文件中的这些数据。
I'm using Express.js and sending the data to the Jade template as follows :
我正在使用 Express.js 并将数据发送到 Jade 模板,如下所示:
var myMongoDbObject = {name : 'stephen'};
res.render('home', { locals: { data : myMongoDbObject } });
Then inside of home.jadeI can do things like :
然后在home.jade 中,我可以执行以下操作:
p Hello #{data.name}!
Which writes out :
其中写出:
Hello stephen!
Now what I want is to also have access to this data object inside a client side JS file so I can manipulate the Object on say a button click before POSTing it back to the server to update the database.
现在我想要的是还可以访问客户端 JS 文件中的这个数据对象,这样我就可以在将对象发布回服务器以更新数据库之前,在单击按钮时操作对象。
I've been able to accomplish this by saving the "data" object inside a hidden input field in the Jade template and then fetching the value of that field inside my client-side JS file.
我已经能够通过将“数据”对象保存在 Jade 模板的隐藏输入字段中,然后在我的客户端 JS 文件中获取该字段的值来实现这一点。
Inside home.jade
内宅.jade
- local_data = JSON.stringify(data) // data coming in from Express.js
input(type='hidden', value=local_data)#myLocalDataObj
Then in my client side JS file I can access local_data like so :
然后在我的客户端 JS 文件中,我可以像这样访问 local_data:
Inside myLocalFile.js
在 myLocalFile.js 中
var localObj = JSON.parse($("#myLocalDataObj").val());
console.log(localObj.name);
However this stringify / parsing business feels messy. I know I can bind the values of my data object to DOM objects in my Jade template and then fetch those values using jQuery, but I'd like to have access to the actual Object that is coming back from Express in my client side JS.
然而,这种字符串化/解析业务感觉很混乱。我知道我可以将我的数据对象的值绑定到我的 Jade 模板中的 DOM 对象,然后使用 jQuery 获取这些值,但我想访问从我的客户端 JS 中的 Express 返回的实际对象。
Is my solution optimal, how would you guys accomplish this?
我的解决方案是否最优,你们将如何实现?
回答by Amberlamps
When rendering is done, only the rendered HTML is send to the client. Therefore no variables will be available anymore. What you could do, is instead of writing the object in the input element output the object as rendered JavaScript:
渲染完成后,仅将渲染的 HTML 发送到客户端。因此,将不再有变量可用。您可以做的是,不是在输入元素中写入对象,而是将对象输出为呈现的 JavaScript:
script(type='text/javascript').
var local_data =!{JSON.stringify(data)}
EDIT: Apparently Jade requires a dot after the first closing parenthesis.
编辑:显然 Jade 在第一个右括号后需要一个点。
回答by jabbermonkey
I do it a little differently. In my contoller I do this:
我做的有点不同。在我的控制器中,我这样做:
res.render('search-directory', {
title: 'My Title',
place_urls: JSON.stringify(placeUrls),
});
And then in the javascript in my jade file I use it like this:
然后在我的玉文件中的 javascript 中,我像这样使用它:
var placeUrls = !{place_urls};
In this example it's used for the twitter bootstrap typeahead plugin. You can then use something like this to parse it if you need to :
在这个例子中,它用于 twitter bootstrap typeahead 插件。如果需要,您可以使用这样的方法来解析它:
jQuery.parseJSON( placeUrls );
Notice also that you can leave out the locals: {} .
另请注意,您可以省略 locals:{}。
回答by AmpT
Using Jade templating:
使用 Jade 模板:
If you are inserting @Amberlamps snippet of code above an included static HTML file, remember to specify !!! 5at the top, to avoid having your styling broken, in views/index.jade:
如果您在包含的静态 HTML 文件上方插入 @Amberlamps 代码片段,请记住指定!!! 5在顶部,以避免您的样式被破坏,在views/index.jade 中:
!!! 5
script(type='text/javascript')
var local_data =!{JSON.stringify(data)}
include ../www/index.html
This will pass in your local_data variable before the actual static HTML page loads, so that the variable is available globally from the start.
这将在实际静态 HTML 页面加载之前传入您的 local_data 变量,以便该变量从一开始就在全局范围内可用。
Serverside (using Jade templating engine) - server.js:
服务器端(使用 Jade 模板引擎)- server.js:
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', ensureAuthenticated, function(request, response){
response.render('index', { data: {currentUser: request.user.id} });
});
app.use(express.static(__dirname + '/www'));
回答by Adrian Miranda
You don't need to pass the locals variables in render call, locals variables are globals. On your pug file call don't put keys expression e.g #{}
. Just use something like:
base(href=base.url)
您不需要在渲染调用中传递局部变量,局部变量是全局变量。在您的 pug 文件调用中,不要放置键表达式,例如#{}
. 只需使用类似的东西:
base(href=base.url)
where base.url
is app.locals.base = { url:'/' };
这里base.url
是app.locals.base = { url:'/' };
回答by Alex Roe
Have you heard of socket.io? (http://socket.io/).
An easy way to access the object from express would be to open a socket between node.js and your javascript. This way data can be easily passed to the client side and then easily manipulated using javascript. The code wouldn't have to be much, simply a socket.emit()
from node.js and a socket.on()
from the client. I think that'd be an effective solution!
你听说过 socket.io 吗?(http://socket.io/)。从 express 访问对象的一种简单方法是在 node.js 和您的 javascript 之间打开一个套接字。通过这种方式,数据可以轻松传递到客户端,然后使用 javascript 轻松操作。代码不必太多,只需一个socket.emit()
来自 node.js 和一个socket.on()
来自客户端。我认为这将是一个有效的解决方案!