javascript - 将变量从 app.js 传递到 ejs 文件到脚本标记中

标签 javascript node.js ejs

我试图将 app.js 中定义的变量传递到 ejs 文件内的脚本标记中。 所以 app.js 简而言之如下所示:

//app.js
var express = require("express")
var app = express()
var request = require("request")



var thelist =[]
app.locals.myVar = thelist.length;

app.get("/", function(req, res){
    res.render("search")
})

app.get("/show/:id", function (req, res) {
    var id = req.params.id;
    thelist.push(id)
    console.log(thelist);
    res.redirect('/')
});

我想传递的变量是app.locals.myVar,实际上这个方法不起作用,我仍然发现myVar没有在ejs文件中定义

ejs 文件在这里:

//search.ejs
<html>
    <head>
        <title>MYMDB</title>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.css">
        <link rel="stylesheet" type="text/css" href="/stylesheets/app.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.js"></script>

    </head>
    <body>


    <a id="show-data" href="/data" class="ui right floated disabled button"> 
      See the table 
    </a>



  <script>
    $('#run').click(function() {
      $('#show-data').removeClass('ui disabled button');
      $('#show-data').addClass('ui loading button');
      setTimeout(function () {      
          $('#show-data').removeClass("ui loading button");
          $('#show-data').addClass('ui basic button')
              }, myVar*2000);
   });
  </script>

  </body>
</html>

正如你所看到的,我尝试使用 myVar - 在服务器端 js 中获取的变量,然后在客户端 js 中使用它。但它似乎无法在 ejs 文件中被识别。

最佳答案

res.render()已参数化。所以,尝试:

res.render("search", {
    myVar: "value"
});

请参阅 Express 文档: app.render() res.render() .

您的 HTML 应该类似于 <%= myVar %>包括在内。

<html>
<body>
    <h1>Hello</h1>
    <p>Lorem</p>
    <script>
        // Print out the variable I got
        console.log(<%= myVar %>)
        // or
        console.log("<%= myVar %>")
    </script>
</body>
</html>

关于javascript - 将变量从 app.js 传递到 ejs 文件到脚本标记中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47145224/

相关文章:

javascript - 无法在 Chrome 中设置/编辑 cookie

javascript - onclick 在 Canvas 中创建随机矩形,不会与现有矩形发生冲突

javascript - postgresql错误: column "" does not exist in where clause

javascript - Sequelize - 如何自动从查询中检索子记录到父表?

javascript - EJS在2个页面之间共享数据

javascript - 将输入字段添加到表单

JavaScript改变类的背景颜色

node.js - Mongoose 调用 .find inside a pre ('save' ) hook

javascript - EJS.JS 引用错误 : title not defined

javascript - Visual Studio Code 无法识别 EJS