如何畫Flot AJAX更新圖

在上一章我們提到了如何畫即時更新圖,而這一章就要教你們如何利用AJAX去後端抓資料回來做即時更新圖.

系統負載即時更新圖(AJAX)

我們直接拿上一章的範例來做修改,在這裡只說明有修改到的部份,有任何不清楚的地方,你也可以隨時回到上一章去查看.

準備資料

首先,因為我們畫的是系統負載圖,所以先建立3個陣列分別叫做cpu和cpuCore及disk,接著就先呼叫initData()建立出初始資料.
 
    
        var cpu = [], cpuCore = [], disk = [];
        var dataset;
        var totalPoints = 100;
        var updateInterval = 1000;
        var now = new Date().getTime();

        function initData() {
            for (var i = 0; i < totalPoints; i++) {
                var temp = [now += updateInterval, 0];

                cpu.push(temp);
                cpuCore.push(temp);
                disk.push(temp);
            }
        }
        

建立更新圖表函式

接著建立一個自定函式叫update(),這個函式需要帶入一個參數叫_data,這個參數就是等下從後端抓回來的資料.在函式裡一開始我們先把儲存資料的陣列裡的第一個項目移除,然後再把從後端抓回來的資料插入到陣列裡,之後我們又再一次的修改dataset裡的資料,我們把label屬性的資料值都加上我們剛抓回來的資料,這樣就可以在圖例中看到數值的變化.最後再重新呼叫$.plot讓圖表重新繪製.
    
        var temp;

        function update(_data) {
            //remove first item of array
            cpu.shift();
            cpuCore.shift();
            disk.shift();

            now += updateInterval

            //add the data retrieve from backend to array
            temp = [now, _data.cpu];
            cpu.push(temp);

            temp = [now, _data.core];
            cpuCore.push(temp);

            temp = [now, _data.disk];
            disk.push(temp);

            //update legend label so users can see the latest value in the legend
            dataset = [
                { label: "CPU:" + _data.cpu + "%", data: cpu, lines: { fill: true, lineWidth: 1.2 }, color: "#00FF00" },
                { label: "Disk:" + _data.disk + "KB", data: disk, color: "#0044FF", bars: { show: true }, yaxis: 2 },
                { label: "CPU Core:" + _data.core + "%", data: cpuCore, lines: { lineWidth: 1.2}, color: "#FF0000" }       
            ];

            //redraw the chart
            $.plot($("#flot-placeholder1"), dataset, options);

            //prepare for next update
            setTimeout(GetData, updateInterval);
        }
        
從後端抓回來的資料物件
    
        {"cpu":47, "core":11, "disk":550}
        

AJAX

我們用jQuery.ajax()來取回後端的資料
    
        function GetData() {
            //set no cache
            $.ajaxSetup({ cache: false });

            $.ajax({
                url: "http://static.jqueryflottutorial.com/AjaxUpdateChart.aspx",
                dataType: 'json',
                success: update,  //if success, call update()
                error: function () {
                    //if fail, prepare next update
                    setTimeout(GetData, updateInterval);
                }
            });
        }
        

後端程式

因為我們沒辦法真正的取得CPU loading的資料,所以我們是用亂數產生資料來模擬,最後再以JSON格式輸出.

C#後端程式(AjaxUpdateChart.aspx)
    
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Controls.Clear();
            Random rnd = new Random();

            int CPUloading = rnd.Next(0, 100);
            int CPUcore = CPUloading - 30 < 0 ? 0 : rnd.Next(0, CPUloading - 30);
            int Disk = rnd.Next(56, 1024);

            Response.Write("{\"cpu\":" + CPUloading + ", \"core\":" + CPUcore + ", \"disk\":" + Disk + "}");
        }
        

練習

本章的完整範例程式碼可以在這裡找到並做線上練習 Go to Example Tester