简体   繁体   中英

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? 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 -%>对我有用。

There are three main EJS Tags

<% %> 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(votes); %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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