使用按钮重新渲染图表

时间:2014-03-14 21:33:35

标签: jquery ajax

我想知道如何点击它时可以重新渲染图表的按钮!所以我不必每隔5分钟刷新一次

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Highstock Example</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">
$(function() {
    var seriesOptions = [],
        yAxisOptions = [],
        seriesCounter = 0,
        names = ['MSFT', 'AAPL', 'GOOG'],
        colors = Highcharts.getOptions().colors;

    $.each(names, function(i, name) {

        $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename='+ name.toLowerCase() +'-c.json&callback=?',   function(data) {

            seriesOptions[i] = {
                name: name,
                data: data
            };

            // As we're loading the data asynchronously, we don't know what order it will arrive. So
            // we keep a counter and create the chart when all the data is loaded.
            seriesCounter++;

            if (seriesCounter == names.length) {
                createChart();
            }
        });
    });



    // create the chart when all data is loaded
    function createChart() {

        $('#container').highcharts('StockChart', {
            chart: {
            },

            rangeSelector: {
                selected: 4
            },

            yAxis: {
                labels: {
                    formatter: function() {
                        return (this.value > 0 ? '+' : '') + this.value + '%';
                    }
                },
                plotLines: [{
                    value: 0,
                    width: 2,
                    color: 'silver'
                }]
            },

            plotOptions: {
                series: {
                    compare: 'percent'
                }
            },

            tooltip: {
                pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
                valueDecimals: 2
            },

            series: seriesOptions
        });
    }

});
        </script>
    </head>
    <body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>

<div id="container" style="height: 500px; min-width: 600px"></div>
    </body>
</html>

1 个答案:

答案 0 :(得分:2)

你可以把你的Javascript代码的第一部分(基本上是你function createChart()之上的所有内容)并将其包装在这样的命名函数中:

function refreshData() {
  ...
}

然后你需要在某个地方添加对这个函数的调用,否则当你的页面加载时它不会被执行。添加以下呼叫,例如在脚本的开头:

refreshData();

现在您可以添加一个简单地调用此新功能的按钮:

<button onclick="refreshData();">Refresh</button>