ajax实现重新绘图,如何画Flot AJAX更新图
在上一章我們提到了如何畫(huà)實(shí)時(shí)更新圖,而這一章就要教你們?nèi)绾卫肁JAX去后端抓數(shù)據(jù)回來(lái)做實(shí)時(shí)更新圖.
系統(tǒng)負(fù)載實(shí)時(shí)更新圖(AJAX)
我們直接拿上一章的范例來(lái)做修改,在這里只說(shuō)明有修改到的部份,有任何不清楚的地方,你也可以隨時(shí)回到上一章去查看.
準(zhǔn)備資料
首先,因?yàn)槲覀儺?huà)的是系統(tǒng)負(fù)載圖,所以先建立3個(gè)數(shù)組分別叫做cpu和cpuCore及disk,接著就先呼叫initData()建立出初始數(shù)據(jù).
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);
}
}
建立更新圖表函式
接著建立一個(gè)自定函式叫update(),這個(gè)函式需要帶入一個(gè)參數(shù)叫_data,這個(gè)參數(shù)就是等下從后端抓回來(lái)的數(shù)據(jù).在函式里一開(kāi)始我們先把儲(chǔ)存數(shù)據(jù)的數(shù)組里的第一個(gè)項(xiàng)目移除,然后再把從后端抓回來(lái)的數(shù)據(jù)插入到數(shù)組里,之后我們又再一次的修改dataset里的數(shù)據(jù),我們把label屬性的數(shù)據(jù)值都加上我們剛抓回來(lái)的數(shù)據(jù),這樣就可以在圖例中看到數(shù)值的變化.最后再重新呼叫$.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);
}
從后端抓回來(lái)的數(shù)據(jù)對(duì)象
{"cpu":47, "core":11, "disk":550}
AJAX
我們用jQuery.ajax()來(lái)取回后端的資料
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);
}
});
}
后端程序
因?yàn)槲覀儧](méi)辦法真正的取得CPU loading的數(shù)據(jù),所以我們是用隨機(jī)數(shù)生成數(shù)據(jù)來(lái)仿真,最后再以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 + "}");
}
總結(jié)
以上是生活随笔為你收集整理的ajax实现重新绘图,如何画Flot AJAX更新图的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c++如何让字符串重复输出_python
- 下一篇: mysql 扫描所有字段_select扫