我是 js 和 spring 的新手,現在我想創建一個 html 儀表板,這個頁面將有一個帶餅圖的小 div。但我無法創建餅圖。我在 youtube 上嘗試了一些教程,但現在我想將值傳遞給 ajax 或類似的東西來獲取餅圖。這是我的代碼:admin_homepage.html:
<div class="col-xl-4 col-lg-5">
<div class="card shadow mb-4">
<!-- Thay chart vào th? div này -->
<div class="card-body">
<div class="chart-pie pt-4 pb-2">
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$.ajax({
/* for pie chart */
url: "admin_home",
success: function(result){
/* pie chart starts here */
var series = [];
var data = [];
for(var i = 0; i < result.length; i ){
var object = {};
object.name = result[i].catName.toUpperCase();
object.y = result[i].catCount;
data.push(object);
}
var seriesObject = {
name: 'Course By Category',
colorByPoint: true,
data: data
};
series.push(seriesObject);
drawPieChart(series);
/* pie chart ends here */
}
});
/* for pie chart */
function drawPieChart(series){
Highcharts.chart('chartContainer', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares in January, 2018'
},
tooltip: {
formatter: function() {
return '<strong>' this.key ': </strong>' this.y;
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.y}'
}
}
},
series: series
});
}
</script>
我的控制器
@GetMapping("/admin_home")
public String viewHomePage(){
// Get list of course and count
List<CountCourse> pieChart = dashBoardRepository.countCourseByCategory();
model.addAttribute("pieChart",pieChart);
return "Admin_Homepage";
}
我想要的只是將 catName、catCount 的值傳遞給餅圖,但我無法幫助我。非常感謝。
uj5u.com熱心網友回復:
因為您使用的是 Thymeleaf 模板,所以不需要使用它$.ajax({...})來檢索餅圖資料。相反,您可以將資料直接提供給 Thymeleaf 模板。
(或者,您可以繼續使用 Ajax 呼叫 - 在這種情況下,Thymeleaf 模板將呈現為 HTML - 然后作為一個單獨的步驟,Ajax 呼叫將獲取餅圖資料。)
下面假設第一種方法(不需要 Ajax):
不需要阿賈克斯
我在問題中使用了您的 Thymeleaf 模板并對腳本進行了一些更改:
我洗掉了 Ajax 呼叫。
我添加了一個 Thymeleaf 變數來保存圖表資料。
這是更新后的腳本:
<script th:inline="javascript">
// this simply wraps the code in a function
// that waits for the DOM to be ready:
(function () {
// this is populated by Thymeleaf:
var pieChartData = /*[[${pieChartData}]]*/ [];
var series = [];
var data = [];
for (var i = 0; i < pieChartData.length; i ) {
var object = {};
object.name = pieChartData[i].catName.toUpperCase();
object.y = pieChartData[i].catCount;
data.push(object);
}
var seriesObject = {
name: 'Course By Category',
colorByPoint: true,
data: data
};
series.push(seriesObject);
drawPieChart(series);
// draw the pie chart:
function drawPieChart(series) {
Highcharts.chart('chartContainer', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Your Heading Goes Here'
},
tooltip: {
formatter: function () {
return '<strong>' this.key ': </strong>' this.y;
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.y}'
}
}
},
// use the series data defined earlier:
series: series
});
}
})();
</script>
關于這個腳本的關鍵點是:
- 腳本標簽如下所示:
<script th:inline="javascript">
這告訴 Thymeleaf 腳本將包含一個或多個 Thymeleaf 運算式。
在我們的例子中,我們有一個運算式——這里是:
var pieChartData = /*[[${pieChartData}]]*/ [];
此語法將導致 Thymeleaf 將pieChartData變數替換為 Java 控制器提供的資料結構。
這是控制器的那部分:
List<CountCourse> pieChartData = dashBoardRepository.countCourseByCategory();
model.addAttribute("pieChartData", pieChartData);
return "admin_homepage";
這假設您有一個CountCourse包含String catName和的物件int catCount。
Thymeleaf 將獲取List<CountCourse> pieChartData資料并為您生成以下 JavaScript(使用我的測驗資料):
var pieChartData = [
{"catName":"Humanities","catCount":123},
{"catName":"Sciences","catCount":145},
{"catName":"Other","catCount":67}
];
之后,我使用與您在 Ajax 成功函式中相同的邏輯將此原始資料轉換為 HightCharts 餅圖資料。
最終結果是以下 HTML 頁面:

與阿賈克斯
If you want to use your Ajax approach instead of this, then you need to build a separate end point which will return the pie chart data directly to the Ajax handler in your JavaScript code.
When you take this approach, you no longer need to use the Thymeleaf attribute:
var pieChartData = /*[[${pieChartData}]]*/ []; // NO LONGER NEEDED
And you no longer need to pass this data to your model in the controller:
model.addAttribute("pieChartData", pieChartData); // NO LONGER NEEDED
Instead, you need to continue using your $.ajax code and you need to build a separate end-point which returns the pieChartData as JSON for that Ajax call:
$.ajax({
/* for pie chart */
url: "piechart_data_json", // some new URL for your JSON pie chart data
...
});
Given you are using Thymeleaf already, I think there is no need for this approach.
Update
Just to explain the following syntax a bit more:
var pieChartData = /*[[${pieChartData}]]*/ [];
It looks like an empty JavaScript array []. But in fact, there is more to it.
The Thymeleaf variable ${pieChartData} receives the data from the controller.
Because the variable is in a <script> tag, it's not sufficient just to use the standard Thymeleaf ${pieChartData} expression. You also have to surround that expression with [[ and ]]. This is because ${pieChartData} is actually valid JavaScript - for example, as used in string interpolation.
That gives us this:
var pieChartData = [[${pieChartData}]];
This is all you need. This will work.
The problem here is, it's not valid JavaScript, so your IDE may highlight it as having a syntax error.
To work around this, you can take one extra step. You can "hide" the expression in a JavaScript comment - and then provide a valid value (the empty array). This keeps the JavaScript syntax checker happy in your IDE.
Thymeleaf will locate the variable inside that comment and remove it - and also remove the placeholder [] value.
That is how Thymeleaf pushes the Java model data into the template in this case.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/335980.html
標籤:javascript 春天 弹簧靴 高图 百里香叶
