jQuery 带有动态ajax数据的JQPlot自动刷新图表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13660883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:51:31  来源:igfitidea点击:

JQPlot auto refresh chart with dynamic ajax data

jqueryjquery-pluginsjqplot

提问by Sangram Mohite

I want to update the chart drawn by jqPlot sequentially in time intervals.

我想按时间间隔按顺序更新 jqPlot 绘制的图表。

My use case is such that the AJAX call returns only a single value. For e.g.:

我的用例是 AJAX 调用只返回一个值。例如:

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

So i want to make plot the graph like:

所以我想绘制图形,如:

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

Can we extract already plotted data in JQPlot and then append this new data set and redraw the graph??

我们可以在 JQPlot 中提取已经绘制的数据,然后附加这个新数据集并重新绘制图形吗?

Can any one help please??

请问有人可以帮忙吗??

回答by charlietfl

You will need to store the data in an array then push new data to the array within each ajax call.

您需要将数据存储在一个数组中,然后在每个 ajax 调用中将新数据推送到该数组中。

Here is a simple demo using a button to start the AJAX updates on a 3 second interval:

这是一个使用按钮以 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")
    }
}

DEMO: http://jsfiddle.net/ZqCXP/

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

回答by shukshin.ivan

Let me add to @charlietfl answer. When you use replot() it takes 2 times longer to redraw, rather than with destroying jqplot. So use destroy() to redraw plot.

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

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

http://jsfiddle.net/zjjvm/it takes 46sec to draw running sine using replot()

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

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

http://jsfiddle.net/p9SbP/it takes 25sec to draw the same using destroy()

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