javascript - 如何将spring数据放入JS Json变量中?
问题描述
我正在使用带有 Spring Boot/Thymeleaf Web 应用程序的条形图 JS 脚本。问题是通过 Thymeleaf 将数据库中的数据输入到以下 JS 变量中:
var myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Algotech", "Provident", "Play", "Namirial", "Avaya", "Maintenance"],
datasets: [{
label: "Godziny",
backgroundColor: "#4e73df",
hoverBackgroundColor: "#2e59d9",
borderColor: "#4e73df",
data: [77, 50, 43, 2, 0, 7],
}],
},
options: {
maintainAspectRatio: false,
layout: {
padding: {
left: 10,
right: 25,
top: 25,
bottom: 0
}
},
scales: {
xAxes: [{
time: {
unit: 'month'
},
gridLines: {
display: false,
drawBorder: false
},
ticks: {
maxTicksLimit: 6
},
maxBarThickness: 25,
}],
yAxes: [{
ticks: {
min: 0,
max: 200,
maxTicksLimit: 5,
padding: 10,
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return number_format(value) + 'g';
}
},
gridLines: {
color: "rgb(234, 236, 244)",
zeroLineColor: "rgb(234, 236, 244)",
drawBorder: false,
borderDash: [2],
zeroLineBorderDash: [2]
}
}],
},
legend: {
display: false
},
tooltips: {
titleMarginBottom: 10,
titleFontColor: '#6e707e',
titleFontSize: 14,
backgroundColor: "rgb(255,255,255)",
bodyFontColor: "#858796",
borderColor: '#dddfeb',
borderWidth: 1,
xPadding: 15,
yPadding: 15,
displayColors: false,
caretPadding: 10,
callbacks: {
label: function(tooltipItem, chart) {
var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
return datasetLabel + ':' + number_format(tooltipItem.yLabel);
}
}
},
}
});
我需要更改此变量的几个部分,例如标签、datasets.data、yAxes.ticks.max 等。我知道与 Thymeleaf 内联,但我无法让它在这里工作。我正确放置了脚本:
<script th:inline="javascript">
/*<![CDATA[*/
the body of the script here
/*]]>*/
</script>
它只在我尝试添加 Thymeleaf 变量之前有效。例如,以下更改会使 Thymeleaf 崩溃:
labels: [/*[[${projects[0].name}]]*/, "Provident", "Play", "Namirial", "Avaya", "Maintenance"],
这甚至不包括各种规模的项目列表的问题。有没有办法用 Java、Thymeleaf 或没有 Thymeleaf 来做到这一点?我开始认为我会更容易使用 PHP 提供数据。
解决方案
好吧,尽管如此尴尬,我不得不求助于 PHP。我已经将 JS 文件转换为一个 PHP 文件,其中包含从 URL 参数填充的所需值,我这样称呼它:
<script src="http://myphpserversaddress/barchart.php?parameter=value"></script>
完美运行,我可以仅使用这个文件处理各种图表。
推荐阅读
- discord.js - 不和谐.js | TypeError:无法读取未定义的属性“位置”
- java - 如何在 Picasso 中正确加载图像
- python - 需要 SQL 查询帮助(使用flask-sqlalchemy)列出所有未在复合多对多表中列出的项目
- python - 如何从多个文件制作子图?Python matplot 库
- angular - 如何在 Angular 的 MatTableModule 中为每一列添加过滤器?
- php - 读取发送到 Laravel 路由的 CSV 文件
- opengl - 有什么方法可以在 hlsl/glsl 片段着色器中按原语获得片段(像素)的百分比覆盖率?
- c - C中的指针和内存算法
- ruby-on-rails - 我怎样才能删除rails对象,每个都做信息
- rust - Rust 中的一个可变引用真的被强制执行了吗?