(我是Web开发的新手,并且)我正在尝试构建一个 node / express 应用程序,该应用程序使用来显示 mysql数据库中的数据> highcharts 。我想要实现的是,我的应用程序页面是动态呈现的,因此,如果我转到某个类别,则相应的数据将被读入数组,然后再次被highcharts 函数(js)使用以显示数据。
我设法在mysql中设置数据,我还发现了如何将数据库连接到我的服务器。
现在,我想将数据读取到服务器端代码中并将其传递到那里的数组中,但是我不明白如何利用客户端js中的数据。高图表功能已定位。
注意:我知道这种方法,您可以在html代码中直接使用查询结果来创建表格并使用例如<%= item.name%>,但这不是我想要实现的。我需要结果作为数组,以将其用作我的图表中的参数。
注2:我已经读到,这必须做一个ajax-get-request,而且我还试图了解它的运行方式,但是我设法做的就是操纵html文本onclick。但是我想要的是,从我的数据库表中动态获取数组以在客户端js中使用它们。关于正确方向的建议,代码段或我的代码更正,我将非常感激!
到目前为止,我的代码:
->路由器(几分钟前可以正常工作,但是我做了更改,现在我不让它工作了)
//Array that i want to pass after reading it in
const years = [];
const arrayone = [];
const arraytwo = [];
const arraythree = [];
//Dynamic route - route_name
router.get('/:route_name', (req, res) => {
const route_name = req.params.route_name;
const querycode = 'SELECT * FROM ?';
//Query
sqldb.query(querycode, route_name, function (err, result, fields) {
if (err) throw err;
for(i=0; i<34; i++){
theyears.push(result[i].years)
thearrayone.push(result[i].dataone)
thearraytwo.push(result[i].datatwo)
thearraythree.push(result[i].datatwo)
}
});
});
->包含高级图表的client-js,(dataovertime是我html中div的ID)
async function thehighchart() {
try{
document.addEventListener('DOMContentLoaded', () => {
Highcharts.chart('dataovertime', {
chart: {
//renderTo: 'dataovertime',
zoomType: 'xy',
events: {
load() {
console.log('chart loaded')
}
}
},
title: {
text: 'Data over time'
},
subtitle: {
text: ''
},
credits: {
text: 'highcharts',
},
xAxis: [{
categories: years,
plotBands: [{ // visualize the end
from: 30.5,
to: 33,
color: 'rgba(68, 170, 213, .2)'
}],
crosshair: true
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}$',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Amount in $',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'Payout Ratio in %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor:
Highcharts.defaultOptions.legend.backgroundColor || // theme
'rgba(255,255,255,0.25)'
},
series: [{
name: 'dataone',
type: 'areaspline',
data: dataone,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'datatwo',
type: 'areaspline',
data: datatwo,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'datathree',
type: 'areaspline',
data: datathree,
tooltip: {
valueSuffix: '$'
}
}]
});
});
} catch (err){console.log(err);}
};
thehighchart();
->数据库的外观,或多或少
years,dataone,datatwo,datathree
1990,1,2,3
1991,2,3,4
1992,3,4,5
1993,4,5,6
理想情况下,数组应类似于
years = [1990, 1991, 1992, 1993];
dataone = [1,2,3,4];
...
我现在已经读了几十篇文章,但是却找不到答案(可能我只是不够聪明,无法理解某些答案),这就是为什么我现在自己问这个问题的原因。 谢谢!