问题
I am trying to pass data from Controller to feed a chart using ChartJS, but when I use a keySet function as labels, the chart is not rendering.
This is the Method from Controller:
@GetMapping("/reports")
public String showDashboard(Model model) {
Map<String, Integer> data = new LinkedHashMap<String, Integer>();
data.put("JAVA", 50);
data.put("Ruby", 20);
data.put("Python", 30);
model.addAttribute("data", data);
return "reports";
}
This is the HTML Code:
<pre>
<body>
<div class="container">
<div th:replace="fragments/navbar :: top"></div>
<div class="row" style="margin-top: 60px">
<div class="chart-container" style="margin: 0 auto; height:20vh; width:40vw">
<canvas id="myChart"></canvas>
</div>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: [[${data.keySet()}]],
datasets: [{
data: [[${data.values()}]],
backgroundColor: [
'rgb(0,255,255)',
'rgb(46,139,87)',
'rgb(255,165,0)'
],
borderColor: [
'rgb(0,255,255)',
'rgb(46,139,87)',
'rgb(255,165,0)'
],
borderWidth: 1
}]
},
});
</script>
</div>
</div>
</body>
</pre>
The chart is not been rendered and this is the output when I check the source code:
<pre>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: [JAVA, Ruby, Python],
datasets: [{
data: [50, 20, 30],
backgroundColor: [
'rgb(0,255,255)',
'rgb(46,139,87)',
'rgb(255,165,0)'
],
borderColor: [
'rgb(0,255,255)',
'rgb(46,139,87)',
'rgb(255,165,0)'
],
borderWidth: 1
}]
},
});
</script>
</pre>
It seems that the function keySet() is not getting values as String.
How can I adjust it to show the values as String and then rendered as Labels?
Regards,
回答1:
I faced similar problem and found that we should use Object.keys(data)
instead of data.keySet()
. So below is the way you can use it
var htmldata = [[${data}]];
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: Object.keys(htmldata),
datasets: [{
data: Object.keys(htmldata).map(function(key) {return htmldata[key];}),
backgroundColor: [
'rgb(0,255,255)',
'rgb(46,139,87)',
'rgb(255,165,0)'
],
borderColor: [
'rgb(0,255,255)',
'rgb(46,139,87)',
'rgb(255,165,0)'
],
borderWidth: 1
}]
},
});
Also your javascript is not thymeleaf readable. Please add th:inline=javascript in script tag and provide CDATA as below
<script th:inline="javascript">
/*<![CDATA[*/
// Here goes my previous script
/*]]>*/
</script>
来源:https://stackoverflow.com/questions/58887502/passing-data-from-controller-to-chartjs