我有一个名为“historicos.ejs”的 View 。在第一次加载时,页面只有 2 个日期选择器来进行范围查询,提交按钮和图表(谷歌图表)为空白。我需要在第二次渲染后(按提交后)进行查询并将数据传递到图表中。
这是放置在我 View 头部的脚本标签
<script type="text/javascript">
// his with query data from the server
var histo = his;
console.log(histo)
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'X');
data.addColumn('number', 'Temperatura (C)');
data.addRows();
var options = {
width: 550,
height: 363,
title: 'Comportamiento de la Temperatura',
hAxis: {
title: 'Tiempo desde '
},
vAxis: {
title: 'Temperatura'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('tem_line'));
chart.draw(data, options);
}
</script>
console.log()
第二行中的命令在浏览器控制台中显示空数组或未定义。
这是“historicos.ejs” Controller
app.get('/historicos', function(req, res) {
res.render("historicos.ejs")
});
app.post('/historicos/buscar', function(req, res) {
//...some query.... query return "his" variable with the data
res.render("historicos.ejs", {
his:JSON.stringity(his)
})
});
注意:我在没有 stringify 的情况下测试了我的代码,并在带有 ejs 的 View 中显示了它 <% %>
而且效果很好。
当我按下提交按钮时,即使数据具有字符串化数据,脚本中的 console.log 也不会显示任何内容。
注意 2:我试过 res.json(JSON.stringify(his)
它运行完美,它在浏览器中显示了来自 mongodb 的所有数据。
所以我的问题是,我该怎么做才能将变量传递到我的脚本中以将数据绘制到图表中?
最佳答案
一个简单的解决方案是将 json 包装在类型为 application/json 的脚本标记中。这将阻止脚本实际运行并允许您使用 DOM 查询文本内容并解析它。
<script id="histo-data" type="application/json">
<%= his %>
</script>
<script type="text/javascript">
var data = document.getElementById('histo-data').textContent.trim()
if(data){
var histo = JSON.parse(data);
console.log(histo)
google.load('visualization', '1', {packages: ['corechart']})
// ...
这里有一个快速演示,显示它适用于一些静态 JSON:http://jsfiddle.net/grnp8n9n/
关于javascript - 提交后如何将数据从 express 传递到脚本标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30217911/