访问Javascript文件中传递的EJS变量 [英] Accessing passed EJS variable in Javascript file
本文介绍了访问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...
-
变体
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屋!
查看全文