我正在研究这个项目,我需要将通过Node js服务器从Mysql数据库传递的数据传递到嵌入了Javascript代码的HTML页面,以使用此数据通过Chart.js库绘制图表。 这是node.js代码:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var plotly = require('plotly')("qzzaz111", "ivonjyk1gd")
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'arduinodb'
});
var count =false;
connection.connect();
/* GET home page. */
router.get('/', function(req, res, next) {
connection.query('SELECT * from Patient', function(err, result) {
if (!err) {
res.render('index', { title: result});
console.log('The solution is: ', result);
}
else {
console.log('Error while performing Query.');
}
这里是HTML页面(index.ejs),我想在脚本中使用“title”数组值来填充图表的“数据”数组
<script src='/javascripts/Chart.min.js'></script>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<canvas id="buyers" width="600" height="400"></canvas>
<br>
<br>
<script>
var buyerData = {
labels : ["January","February","March","April","May","June"],
datasets : [
{
fillColor : "rgba(172,194,132,0.4)",
strokeColor : "#ACC26D",
pointColor : "#fff",
pointStrokeColor : "#9DB86D",
data : [ 87,156,99,251,305,247]
}
]
}
var buyers = document.getElementById('buyers').getContext('2d');
new Chart(buyers).Line(buyerData);
</script>
所以,如果我试图直接使用“标题”,页面中就不会显示任何内容(空白页面)。 任何解决方案?
答案 0 :(得分:0)
如果您的数据库中的数据是int:
数组,请尝试使用此代码<script src='/javascripts/Chart.min.js'></script>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<canvas id="buyers" width="600" height="400"></canvas>
<br>
<br>
<script>
var buyerData = {
labels : ["January","February","March","April","May","June"],
datasets : [
{
fillColor : "rgba(172,194,132,0.4)",
strokeColor : "#ACC26D",
pointColor : "#fff",
pointStrokeColor : "#9DB86D",
data : [<%= title %>] //here
}
]
}
var buyers = document.getElementById('buyers').getContext('2d');
new Chart(buyers).Line(buyerData);
</script>
如果您的数据不是需要映射的数组,例如。使用lodash地图:
router.get('/', function(req, res, next) {
connection.query('SELECT * from Patient', function(err, result) {
if (!err) {
var data = .map(result, function(n) { //here using lodash
return n.id;
});
res.render('index', {
title: data
});
console.log('The solution is: ', result);
} else {
console.log('Error while performing Query.');
}