如何画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