res.render将数据发送到EJS文件并在普通的javascript中使用它

时间:2017-12-17 16:56:58

标签: javascript node.js express ejs

我在快递和res.render()功能中有下一个GET功能我向EJS文件发送我想要使用的数据,现在我的问题是如何使用我的数据&# 39;在同一个EJS文件中用普通javascript发送到EJS文件? GET功能:



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 });
		});
	});
});




以及如何使用数据的示例:



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

3 个答案:

答案 0 :(得分:0)

使用<% %>标记不会评估表达式。请改用<%= votes %>

答案 1 :(得分:0)

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

答案 2 :(得分:0)

有三个主要的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 %>

如果您想在浏览器控制台中控制登录,可以使用...

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

如果你想将console.log改为服务器端控制台,只需使用...

<% console.log(votes); %>
相关问题