【问题标题】:JQPlot auto refresh chart with dynamic ajax data带有动态ajax数据的JQPlot自动刷新图表
【发布时间】:2012-11-19 14:21:51
【问题描述】:

我想按时间间隔顺序更新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 中提取已经绘制的数据,然后附加这个新数据集并重新绘制图形吗??

有人可以帮忙吗?

【问题讨论】:

    标签: jquery jquery-plugins jqplot


    【解决方案1】:

    您需要将数据存储在一个数组中,然后在每个 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 一起使用,我必须在其中销毁旧视图。它工作正常,但是在使用更新的数据重新绘制图形后发生滚动时看起来并不酷。您对此有什么解决方案吗?
    【解决方案2】:

    让我添加到@charlietfl 的答案。当您使用 replot() 时,重绘需要 2 倍的时间,而不是破坏 jqplot。所以使用 destroy() 重绘绘图。

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

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

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

    http://jsfiddle.net/p9SbP/ 使用 destroy() 绘制相同的图像需要 25 秒

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2011-03-24
      相关资源
      最近更新 更多