在客户端 JavaScript 中访问 Express.js 局部变量 [英] Accessing Express.js local variables in client side JavaScript

查看:26
本文介绍了在客户端 JavaScript 中访问 Express.js 局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很好奇我的做法是否正确,如果不正确,你们会如何处理.

Curious if I'm doing this right and if not how you guys would approach this.

我有一个 Jade 模板,需要呈现从 MongoDB 数据库中检索到的一些数据,我还需要访问客户端 JavaScript 文件中的这些数据.

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.

我正在使用 Express.js 并将数据发送到 Jade 模板,如下所示:

I'm using Express.js and sending the data to the Jade template as follows :

var myMongoDbObject = {name : 'stephen'};
res.render('home', { locals: { data : myMongoDbObject } });

然后在 home.jade 里面我可以做这样的事情:

Then inside of home.jade I can do things like :

p Hello #{data.name}!

写出来的:

Hello stephen!

现在我想要的是还可以访问客户端 JS 文件中的这个数据对象,这样我就可以在将它发送回服务器以更新数据库之前操作对象,比如单击按钮.

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.

我已经能够通过将数据"对象保存在 Jade 模板的隐藏输入字段中,然后在我的客户端 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.

home.jade 内部

- local_data = JSON.stringify(data) // data coming in from Express.js
input(type='hidden', value=local_data)#myLocalDataObj

然后在我的客户端 JS 文件中,我可以像这样访问 local_data :

Then in my client side JS file I can access local_data like so :

在 myLocalFile.js 中

var localObj = JSON.parse($("#myLocalDataObj").val());
console.log(localObj.name);

然而,这个字符串化/解析业务感觉很混乱.我知道我可以将我的数据对象的值绑定到我的 Jade 模板中的 DOM 对象,然后使用 jQuery 获取这些值,但我想在我的客户端 JS 中访问从 Express 返回的实际对象.

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.

我的解决方案是否最优,你们会如何实现?

Is my solution optimal, how would you guys accomplish this?

推荐答案

渲染完成后,只会将渲染的 HTML 发送到客户端.因此,将不再有变量可用.您可以做的是,不是在输入元素中写入对象,而是将对象输出为呈现的 JavaScript:

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:

script(type='text/javascript').
    var local_data =!{JSON.stringify(data)}

显然 Jade 在第一个右括号后需要一个点.

Apparently Jade requires a dot after the first closing parenthesis.

这篇关于在客户端 JavaScript 中访问 Express.js 局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆