访问Javascript文件中传递的EJS变量 [英] Accessing passed EJS variable in Javascript file

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

问题描述

RESTful路由js文件:

RESTful routes js file:

// index route - show all todos
router.get("/", middleware.isLoggedIn,function(req,res) {
  Todo.find({ "author.id" : req.user._id}, function(err, allTodos) {
    if(err) {
      console.log(err);
    } else {
      res.render("todo/index", {todos: allTodos});
    }
  });        
});

我的index.ejs文件具有:

My index.ejs file has:

<script src="/scripts/todoCalendar.js"></script>

body标记末尾的

,我想访问我的todoCalendar.js文件中的传递变量todos. 我试过了

at the end of the body tag and I want to access the passed variable todos inside my todoCalendar.js file. I tried putting

<script>
  var x= <%= todos %>
</script>

但是当我尝试在todoCalendar.js文件中执行console.log(x)时,它说x是未定义的.

but it says x is undefined when i try to do a console.log(x) inside my todoCalendar.js file.

非常感谢您的帮助.

推荐答案

解决问题的三种方法...

Three way to solve the problem...

  1. 变体

  1. variant

<script>
    var x = "<%= todos %>";
    console.log(x); 
</script>

  • 变体

  • variant

    <script>
        var x = "<%- todos %>";
        console.log(x); 
    </script>
    

  • 变体[XD]

  • variant [XD]

    HTML:

    <p id="yy" style="display:none"><%= todos %></p>
    

    JavaScript:

    Javascript:

    <script>
        var x = document.getElementById("yy").innerText;
        console.log(x); 
    </script>
    

  • 这篇关于访问Javascript文件中传递的EJS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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