简体   繁体   English

res.render将数据发送到EJS文件并在纯JavaScript中使用它

[英]res.render send data to EJS file and using it in plain javascript

I have this next GET function in express and in the res.render() function i'm sending to the EJS file the data i want to use, now my question is how can i use the data that i've sent to the EJS file in plain javascript in the same EJS file? 我在Express和res.render()函数中有下一个GET函数,我正在将要使用的数据发送到EJS文件,现在我的问题是我如何使用已发送到EJS的数据同一EJS文件中的纯javascript文件? GET Funtion: 获得功能:

 router.get('/:id', (req, res) => { let pollId = req.params.id; Poll.findById(pollId, (err, poll) => { if(err) throw err; Vote.find(pollId, (err, votes) => { res.render('vote', {user: req.user, poll: poll, voteFail: req.flash('voteFail'),votes: votes }); }); }); }); 

And an example of how i want to use the data: 以及我想如何使用数据的示例:

 <script type="text/javascript"> console.log(<%votes%>); </script> 

Using <% %> tags does not evaluate the expression. 使用<% %>标记不会评估表达式。 Use <%= votes %> instead. 请使用<%= votes %>

尝试使用<%- votes -%>对我有用。

There are three main EJS Tags 有三个主要的EJS标签

<% %> and <%- %> and <%= %>

<% These will run script server side - There is no output - The user will not see this %> 

<%- These will inject javascript value into your html, unsanitized - you can pass html this way. %>

<%= These tags will inject the javascript value into your html, sanitized - html tags will appear as strings %>

If you want to console log in the browser console you can use... 如果要控制台登录浏览器控制台,则可以使用...

<script>
   console.log( <%-votes%> );
</script>

If you want to console.log to the server side console simply use... 如果要console.log到服务器端控制台,只需使用...

<% console.log(votes); %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM