ExpressJS将变量传递给JavaScript [英] ExpressJS Pass variables to JavaScript

查看:106
本文介绍了ExpressJS将变量传递给JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全迷失了这个;我正在使用NodeJS获取JSON,我需要将变量传递给我的页面,并使用JavaScript使用数据。

 应用程序.get('/ test',function(req,res){
res.render('testPage',{
myVar:'My Data'
});

这是我的Express代码(非常简单的测试目的);现在使用JADE我想收集我所知道的数据在页面上呈现简单的

  p = myVar 

但是,我需要能够使用JavaScript收集这些数据(如果可能的话在.js文件中),但是现在只需在Alert框中显示变量, p>

  alert(#{myVar})

如果有任何人可以帮助你,我们可以帮助很多人。

解决方案

请尝试以下操作:

  alert('!{myVar}')

对d进行JSON编码是个好主意ata如果不只是一个字符串。

  alert('!{JSON.stringify(myVar)}')


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'
    });

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

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

alert(#{myVar})

And many others if anyone can help be much appreciated

解决方案

Try the following:

alert('!{myVar}')

It's a good idea to JSON encode the data if is more than just a string.

alert('!{JSON.stringify(myVar)}')

这篇关于ExpressJS将变量传递给JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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