【发布时间】:2018-04-01 02:28:18
【问题描述】:
我正在运行一个快速应用程序,使用 EJS 作为我的模板引擎。 但是我在将变量从我的服务器传递到我的客户端脚本时遇到了困难。
我已尝试使用 JSON.stringify 和 JSON.parse,正如其他 stackoverflow 问题中所建议的那样。
服务器端代码:
.post(function (req, res) { //Is there a better way to update votes than using post request?
if (req.body.buttoncolor === 'red') {
Dilemma.findByIdAndUpdate(dilemmaID, {
$inc: {
red_dilemma_votes: 1
}
}, function (err, dilemma) {
if (err) {
console.log('Error updating votes on dilemma in root: ' + err);
} else {
res.render('index', {
dilemma: dilemma,
buttonclicked: JSON.stringify('red')
})
console.log(JSON.stringify('red'));
console.log('Data from post request in root: ' + dilemma);
}
});
}
客户端代码:
<%
if (typeof(buttonclicked) !== "undefined" && buttonclicked){
%>
<script>
var buttonclicked = JSON.parse(<%= buttonclicked %>);
console.log('buttonclicked in script: ' + buttonclicked);
showResults(<%= buttonclicked %>);
</script>
<%}
%>
客户是这样解释的:
<script>
var buttonclicked = JSON.parse("red");
console.log('buttonclicked in script: ' + buttonclicked);
showResults("red");
</script>
【问题讨论】:
标签: json node.js parsing variables express