jQuery 使用 Highcharts 通过 JSON 重新加载图表数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4210879/
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 16:50:22  来源:igfitidea点击:

Reload chart data via JSON with Highcharts

jqueryjsonhighcharts

提问by NightMICU

I am trying to reload the data for a Highcharts chart via JSON based on a button click elsewhere in the page. Initially I would like to display a default set of data (spending by category) but then load new data based on user input (spending by month, for example). The easiest way I can think of to output the JSON from the server is by passing a GET request to the PHP page, for example $.get('/dough/includes/live-chart.php?mode=month', retrieving this value from the button's ID attribute.

我正在尝试基于页面其他地方的按钮单击通过 JSON 重新加载 Highcharts 图表的数据。最初,我想显示一组默认数据(按类别支出),然后根据用户输入(例如按月支出)加载新数据。我能想到的从服务器输出 JSON 的最简单方法是将 GET 请求传递到 PHP 页面,例如$.get('/dough/includes/live-chart.php?mode=month',检索这个来自按钮 ID 属性的值。

Here is what I have so far to retrieve the default data (spending by category). Need to find how to load completely different data into the pie chart, based on user input, on demand:

这是我迄今为止检索默认数据(按类别支出)的内容。需要找到如何根据用户输入,按需将完全不同的数据加载到饼图中:

$(document).ready(function() {
            //This is an example of how I would retrieve the value for the button
            $(".clickMe").click(function() {
                var clickID = $(this).attr("id");
            });
            var options = {
                chart: {
                    renderTo: 'graph-container',
                    margin: [10, 175, 40, 40]
                },
                title: {
                    text: 'Spending by Category'
                },
                plotArea: {
                    shadow: null,
                    borderWidth: null,
                    backgroundColor: null
                },
                tooltip: {
                    formatter: function() {
                        return '<b>'+ this.point.name +'</b>: $'+ this.y;
                    }
                },
                credits: {
                    enabled: false
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            formatter: function() {
                                if (this.y > 5) return '$' + this.y;
                            },
                            color: 'white',
                            style: {
                                font: '13px Trebuchet MS, Verdana, sans-serif'
                            }
                        }
                    }
                },
                legend: {
                    layout: 'vertical',
                    style: {
                        left: 'auto',
                        bottom: 'auto',
                        right: '50px',
                        top: '100px'
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Spending',
                    data: []
                }]
            };
            $.get('/dough/includes/live-chart.php', function(data) {
            var lines = data.split('\n');
            $.each(lines, function(lineNo, line) {
                var items = line.split(',');
                var data = {};
                $.each(items, function(itemNo, item) {
                    if (itemNo === 0) {
                        data.name = item;
                    } else {
                        data.y = parseFloat(item);
                    }
                });
                options.series[0].data.push(data);
            });
            // Create the chart
            var chart = new Highcharts.Chart(options);
        });
        });

Any help would be greatly appreciated

任何帮助将不胜感激

EDIT

编辑

Here is the updated Javascript thanks to Robodude. John, you have me on the right track here - thanks! I'm now getting stuck with how to replace the data on the chart from the AJAX request. I must admit that the code following the $.get() is most likely from sample code, I do not fully understand what is going on when it is run - perhaps there is a better way to format the data?

由于 Robodude,这是更新的 Javascript。约翰,你让我走在正确的轨道上 - 谢谢!我现在遇到了如何从 AJAX 请求替换图表上的数据的问题。我必须承认 $.get() 后面的代码很可能来自示例代码,我不完全理解它运行时发生了什么 - 也许有更好的方法来格式化数据?

I was able to make some progress in that the chart now loads new data but it is added on top of what is already there. I suspect that the culprit is this line:

我能够取得一些进展,因为图表现在加载了新数据,但它被添加到已经存在的数据之上。我怀疑罪魁祸首是这一行:

options.series[0].data.push(data);

I tried options.series[0].setData(data); but nothing happens. On the bright side, the AJAX request works flawlessly based on the value of the select menu and there are no Javascript errors. Here is the code in question, sans chart options:

我试过 options.series[0].setData(data); 但什么也没有发生。从好的方面来说,AJAX 请求基于选择菜单的值完美运行,并且没有 Javascript 错误。这是有问题的代码,没有图表选项:

$.get('/dough/includes/live-chart.php?mode=cat', function(data) {
            var lines = data.split('\n');
            $.each(lines, function(lineNo, line) {
                var items = line.split(',');
                var data = {};
                $.each(items, function(itemNo, item) {
                    if (itemNo === 0) {
                        data.name = item;
                    } else {
                        data.y = parseFloat(item);
                    }
                });
                options.series[0].data.push(data);
            });
            // Create the chart
            var chart = new Highcharts.Chart(options);
        });
        $("#loadChart").click(function() {
            var loadChartData = $("#chartCat").val();
                $.get('/dough/includes/live-chart.php?mode=' + loadChartData, function(data) {
                var lines = data.split('\n');
                $.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                });
                // Create the chart
                var chart = new Highcharts.Chart(options);
            });
        });
    });

EDIT 2This is the format that the chart is pulling from - very simple, category name and value with \n after each.

编辑 2这是图表从中提取的格式 - 非常简单,类别名称和值,每个后面都有 \n。

Coffee, 4.08
Dining Out, 5.05
Dining: ODU, 5.97
Dining: Work, 38.41
Entertainment, 4.14
Gas, 79.65
Groceries, 228.23
Household, 11.21
Misc, 12.20
Snacks, 20.27

采纳答案by RoboKozo

EDIT: The response down below is more correct!

编辑:下面的回答更正确!

https://stackoverflow.com/a/8408466/387285

https://stackoverflow.com/a/8408466/387285

http://www.highcharts.com/ref/#series-object

http://www.highcharts.com/ref/#series-object

HTML:

HTML:

<SELECT id="list">
<OPTION VALUE="A">Data Set A
<OPTION VALUE="B">Data Set B
</SELECT>
<button id="change">Refresh Table</button>

<div id="container" style="height: 400px"></div>

Javascript:

Javascript:

var options = {
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'spline'
    },
    series: []
};

$("#change").click(function() {
    if ($("#list").val() == "A") {
        options.series = [{name: 'A', data: [1,2,3,2,1]}]
        // $.get('/dough/includes/live-chart.php?mode=month'
    } else {
        options.series = [{name: 'B', data: [3,2,1,2,3]}]
        // $.get('/dough/includes/live-chart.php?mode=newmode'
    } 

    var chart = new Highcharts.Chart(options);    
});

This is a very simple example since I don't have my files here with me but the basic idea is that every time the user selects new options for the stuff they want to see, you're going to have replace the .series data object with the new information from your server and then recreate the chart using the new Highcharts.Chart();.

这是一个非常简单的例子,因为我没有随身携带我的文件,但基本思想是每次用户为他们想要查看的内容选择新选项时,您将替换 .series 数据对象使用来自服务器的新信息,然后使用新的 Highcharts.Chart(); 重新创建图表。

Hope this helps! John

希望这可以帮助!约翰

EDIT:

编辑:

Check this out, its from something I've worked on in the past:

看看这个,它来自我过去工作过的东西:

$("table#tblGeneralInfo2 > tbody > tr").each(function (index) {
    if (index != 0) {
        var chartnumbervalue = parseInt($(this).find("td:last").text());
        var charttextvalue = $(this).find("td:first").text();
        chartoptions.series[0].data.push([charttextvalue, chartnumbervalue]);
    }
});

I had a table with information in the first and last tds that I needed to add to the pie chart. I loop through each of the rows and push in the values. Note: I use chartoptions.series[0].data since pie charts only have 1 series.

我有一个表格,其中包含需要添加到饼图中的第一个和最后一个 td 中的信息。我遍历每一行并推入值。注意:我使用 chartoptions.series[0].data 因为饼图只有 1 个系列。

回答by jspooner

The other answers didn't work for me. I found the answer in their documentation:

其他答案对我不起作用。我在他们的文档中找到了答案:

http://api.highcharts.com/highcharts#Series

http://api.highcharts.com/highcharts#Series

Using this method (see JSFiddle example):

使用此方法(参见 JSFiddle 示例):

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container'
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]        
    }]
});

// the button action
$('#button').click(function() {
    chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
});

回答by mcoffey

You need to clear the old array out before you push the new data in. There are many ways to accomplish this but I used this one:

在推送新数据之前,您需要清除旧数组。有很多方法可以实现这一点,但我使用了这个:

options.series[0].data.length = 0;

So your code should look like this:

所以你的代码应该是这样的:

options.series[0].data.length = 0;
$.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                });

Now when the button is clicked the old data is purged and only the new data should show up. Hope that helps.

现在,当单击按钮时,旧数据将被清除,只应显示新数据。希望有帮助。

回答by Abruzzi

Actually maybe you should choose the function updateis better.
Here's the document of function updatehttp://api.highcharts.com/highcharts#Series.update

其实也许你应该选择功能update更好的。
这是函数的文档updatehttp://api.highcharts.com/highcharts#Series.update

You can just type code like below:

您可以输入如下代码:

chart.series[0].update({data: [1,2,3,4,5]})

chart.series[0].update({data: [1,2,3,4,5]})

These code will merge the origin option, and update the changed data.

这些代码将合并原点选项,并更新更改的数据。

回答by Dipanjan

Correct answer is:

正确答案是:

$.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                    data = {};
                });

You need to flush the 'data' array.

您需要刷新“数据”数组。

data = {};

回答by Maanas Royy

You can always load a json data

你总是可以加载一个json数据

here i defined Chart as namespace

在这里我将 Chart 定义为命名空间

 $.getJSON('data.json', function(data){
                Chart.options.series[0].data = data[0].data;
                Chart.options.series[1].data = data[1].data;
                Chart.options.series[2].data = data[2].data;

                var chart = new Highcharts.Chart(Chart.options);

            });

回答by Jamsi

If you areusing push to push the data to the option.series dynamically .. just use

如果您正在使用推推数据来动态的option.series ..只是使用

options.series = [];  

to clear it.

清除它。

options.series = [];
$("#change").click(function(){
}

回答by Amrit Shrestha

data = [150,300]; // data from ajax or any other way chart.series[0].setData(data, true);

data = [150,300]; // data from ajax or any other way chart.series[0].setData(data, true);

The setDatawill call redraw method.

setData会调用再拉法。

Reference: http://api.highcharts.com/highcharts/Series.setData

参考:http: //api.highcharts.com/highcharts/Series.setData