JQPlot如何使用动态Ajax数据自动刷新图表

7

我希望能够按照时间间隔逐步更新由jqPlot绘制的图表。

我的使用情况是,AJAX调用仅返回单个值。例如:

1st AJAX call: 20
2nd AJAX call: 30
3rd AJAX call: 40
4th AJAX call: 32

我想要绘制类似于以下的图表:

First: only 20
Second: 20,30
Third: 20,30,40
Fourth: 20,30,40,32

我们能否提取已绘制的 JQPlot 数据集,然后附加新的数据集并重新绘制图形?请问有人可以帮忙吗?
2个回答

14
您需要将数据存储在数组中,然后在每个 ajax 调用中将新数据推送到该数组中。
以下是一个简单的演示,使用按钮在 3 秒间隔内启动 AJAX 更新:
/* store empty array or array of original data to plot on page load */

var storedData = [3, 7];

/* initialize plot*/

var plot1;
renderGraph();

$('button').click( function(){
    doUpdate();
    $(this).hide();
});

function renderGraph() {
    if (plot1) {
        plot1.destroy();
    }
    plot1 = $.jqplot('chart1', [storedData]);
}
/* sample data for demo*/   
var newData = [9, 1, 4, 6, 8, 2, 5];


function doUpdate() {
    if (newData.length) {
        /* used to pull new number from sample data for demo*/
        var val = newData.shift();

        $.post('/echo/html/', {
            html: val
        }, function(response) {
            var newVal = new Number(response); /* update storedData array*/
            storedData.push(newVal);
            renderGraph();               
            setTimeout(doUpdate, 3000)
        })

    } else {
        alert("All Done")
    }
}

演示:http://jsfiddle.net/ZqCXP/


我正在使用backbone.js,其中我必须销毁旧视图。它的工作正常,但在使用更新后的数据重新绘制图表后滚动时看起来不太好。你有什么解决方案吗? - Neha Choudhary

5

我想补充一下@charlietfl的回答。当你使用replot()函数重新绘制图表时,它需要比销毁jqplot对象再重新创建更长的时间才能完成重绘。因此,建议使用destroy()函数将原有的jqplot对象销毁后再创建新的对象来实现重绘。

$.jqplot('chart1', [storedData]).replot();

http://jsfiddle.net/zjjvm/ 使用replot()绘制运行正弦图需要46秒。

plot1.destroy();
plot1 = $.jqplot('chart1', [storedData])

http://jsfiddle.net/p9SbP/ 使用 destroy() 方法绘制相同的内容需要 25 秒。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接