<script src="Js/Index/jquery-1.5.2.min.js"></script>
<script src="Js/Index/highcharts.js"></script>
<script src="Js/Index/exporting.js"></script>
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'divChart', // 容器 ID
defaultSeriesType: 'line', // 折線圖
plotBackgroundColor: null,
plotBorderWidth: null
},
title: { text: '24小時負荷曲線' },
subtitle: { text: '' },
xAxis: {
categories: ['00','01','02','03','04','05','06','07','08','09','10','11',
'12','13','14','15','16','17','18','19','20','21','22','23'],
labels: { rotation: -45, align: 'right', style: { font: 'normal 12px 宋體' } }
},
yAxis: { title: { text: 'MW' } },
tooltip: {
enabled: true,
formatter: function() {
return '<b>' + this.x + '</b><br/>' + this.series.name + ': ' + Highcharts.numberFormat(this.y, 1);
}
},
plotOptions: {
line: { dataLabels: { enabled: true }, enableMouseTracking: true }
},
series: [
{ name: '1號機組', data: Array(24).fill(0) },
{ name: '2號機組', data: Array(24).fill(0) }
]
});
// 3. 定時輪詢更新數據
function getForm() {
$.ajax({
type: "POST", url: "WebServiceFH.asmx/GetLoadEveryHourByOne",
contentType: "application/json", dataType: "json",
success: function(data) {
var arr = [data.Load0, data.Load1, ..., data.Load23]; // 24 項
chart.series[0].setData(arr); // 關鍵:setData 熱更新
},
error: function() { alert("讀取數據出錯!"); }
});
$.ajax({ // 第二台機組
type: "POST", url: "WebServiceFH.asmx/GetLoadEveryHourByTwo",
contentType: "application/json", dataType: "json",
success: function(data) {
var arr = [data.Load0, data.Load1, ..., data.Load23];
chart.series[1].setData(arr);
},
error: function() { alert("讀取數據出錯!"); }
});
}
getForm(); // 首次載入
setInterval(getForm, 600000); // 每 10 分鐘輪詢
});
<div id="divChart"></div>
| 技術點 | 說明 |
|---|---|
chart.series[i].setData(newData) | Highcharts 核心熱更新 API,無需銷毀重建圖表,效能極佳 |
| 雙 AJAX 並行 | 兩台機組數據獨立請求,互不阻塞 |
| 數據陣列對應 | 後端回傳物件屬性 Load0~Load23 需手動映射為陣列順序 |
setInterval 輪詢 | 簡單可靠的即時更新機制;現代可改用 WebSocket/Server-Sent Events |
| Tooltip Formatter | 自訂懸浮提示內容,支援 HTML |
fetch + async/await 簡化 AJAX 邏輯。[load0, load1, ...] 避免前端手動映射。Highcharts.setOptions({ time: { timezone: 'Asia/Taipei' } }) 處理時區。chart.reflow() 適應容器尺寸變化。Highcharts setData 方法是實現高效能即時圖表的關鍵。結合 jQuery AJAX 輪詢(或 WebSocket),可快速構建監控大屏、儀表板等即時數據視覺化應用。