gpt4 book ai didi

javascript - ChartJS - 从服务器端注入(inject)数据

转载 作者:行者123 更新时间:2023-12-03 03:07:15 24 4
gpt4 key购买 nike

我在我的 Node 应用程序中使用 chartJS 2.7.1

我的 pug 文件如下所示:

extends layouts/_layout.pug

block content
.page-title
div
h1
i.fa.fa-dashboard
| Bitcoin Price Example

.row

.col-md-12
.card
h3.card-title Loading local bitcoin file
canvas#canvas.chartjs-render-monitor(style='display: block; width: 1000px; height: 500px;', width='1000', height='500')
console.log(data)

block specific-js
script(type='text/javascript', src="js/chartJS_price.js")
script(type='text/javascript', src="js/plugins/chart.js") // The Chart JS library

chartJS_price.js 文件如下所示:

const lineChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "Price",
borderColor: 'rgba(255,99,132,1)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
fill: false,
data: [
5,
6
],
yAxisID: "y-axis-1",
}, {
label: "MarketCap",
borderColor: 'rgba(54, 162, 235, 0.2)',
backgroundColor: 'rgba(54, 162, 235, 1)',
fill: false,
data: [
1,
3
],
yAxisID: "y-axis-2"
}]
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = Chart.Line(ctx, {
data: lineChartData,
options: {
responsive: true,
hoverMode: 'index',
stacked: false,
title: {
display: true,
text: 'Bitcoin Price and MarketCap'
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
}],
}
}
});
};

我的 app.js 文件中的路由如下所示:

// routes
app.get('/price', (req, res) => {
const priceData = JSON.parse(fs.readFileSync(path.join(__dirname, './data/prices.json'), 'utf8'))
res.render('prices', {
priceData,
})
})

如您所见,我正在 route 中加载 price 数据并将其传递给view。我正在使用自定义 chartjs 规范将脚本加载到我的 pug 文件中。

有关如何将我的 priceData 变量从我的路线注入(inject)到 pug 模板中加载的 chartJS_price.js 的任何建议。

有什么建议吗?

最佳答案

pug 文件没问题,您只需对 chart_price.js 文件进行一些更改,通过 ajax 向服务器发出请求,并在您的服务器文件中,而不是渲染该文件、读取文件内容并使用res.send(//你的json数据).

关于javascript - ChartJS - 从服务器端注入(inject)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47111956/

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