gpt4 book ai didi

javascript - 如何将值从 Node.js 服务器传递到 HTML 页面内嵌入的 Javascript 代码?

转载 作者:行者123 更新时间:2023-11-29 21:55:33 25 4
gpt4 key购买 nike

我正在开发这个项目,其中我需要将通过 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),我想在其中使用脚本内的“标题”数组值来填充图表的“数据”数组

<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>

所以,如果我尝试直接使用“标题”,页面(空白页面)中不会显示任何内容。有什么解决办法吗?

最佳答案

如果数据库中的数据是 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 map :

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

关于javascript - 如何将值从 Node.js 服务器传递到 HTML 页面内嵌入的 Javascript 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33186977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com