通过JSON与Highcharts重新载入海图数据 [英] Reload chart data via JSON with Highcharts

查看:75
本文介绍了通过JSON与Highcharts重新载入海图数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是我迄今为止检索默认数据(按类别划分的花费)。如何根据用户输入按需将完全不同的数据加载到饼图中:

  $(document).ready(函数(){
//这是我如何检索按钮
$(。clickMe)的值的示例。click(function(){
var clickID = $ (this).attr(id);
});
var options = {
chart:{
renderTo:'graph-container',
margin :[10,175,40,40]
},
标题:{
text:'按类别开支ory'
},
plotArea:{
shadow:null,
borderWidth:null,
backgroundColor:null
},
tooltip: {
formatter:function(){
return'< b>'+ this.point.name +'< / b>:$'+ this.y;
}
},
学分:{
启用:false
},
plotOptions:{
pie:{
allowPointSelect :true,
cursor:'pointer',
dataLabels:{
enabled:true,
formatter:function(){
if(this.y> 5 )返回'$'+ this.y;
},
color:'white',
style:{
font:'13px Trebuchet MS,Verdana,sans-serif'
}
}
}
},
图例:{
layout:'vertical',
style:{
left:'auto',
bottom :'auto',
右:'50px',
top:'100px'
}
},
系列:[{
type:' pie',
name:'Spending',
data:[]
}]
};
$ .get('/ dough / includes / live-chart.php',function(data){
var lines = data.split('\\\
');
$。 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);
});
//创建图表
var chart = new Highcharts.Chart(options);
});
});

任何帮助将不胜感激

编辑



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

我现在可以取得一些进展,现在图表会加载新的数据,但它已经添加到已有的数据的顶端。我怀疑是罪魁祸首:


我尝试了options.series [0] .setData(data);但没有任何反应。好的一面,AJAX请求基于选择菜单的值完美工作,并且没有Javascript错误。这里是有问题的代码,无图表选项:

  $。get('/ dough / includes / live-chart.php ?mode = cat',function(data){
var lines = data.split('\\\
');
$ .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);
}
});
选项。系列[0] .data.push(数据);
});
//创建图表
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('\\\
');
$ .each(lines,function(lineNo,行){
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);
});
//创建图表
var chart = new Highcharts.Chart(options);
});
});
});

编辑2
这是图表的格式从 - 非常简单,类别名称和价值拉回来\ n每个后。

 咖啡,4.08 
外出就餐,5.05
餐饮:ODU,5.97
餐饮:工作,38.41
娱乐,4.14
燃气,79.65
杂货,228.23
家庭,11.21
Misc,12.20
零食,20.27


解决方案

编辑:下面的回应是更正确的!



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



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



HTML:

 < SELECT id =list> 
< OPTION VALUE =A>数据集A
< OPTION VALUE =B>数据集B
< / SELECT>
< button id =change>刷新表< / button>

< div id =containerstyle =height:400px>< / div>

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);
});

这是一个非常简单的例子,因为我没有我的文件在这里,但基本的想法是每次用户为他们想要查看的东西选择新选项时,都将使用服务器中的新信息替换.series数据对象,然后使用新的Highcharts.Chart();。重新创建图表。 / p>

希望这会有所帮助!
John



编辑:



检查了这一点,它来自我过去一直在做的事情:

  $(table#tblGeneralInfo2> tbody> ()())。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]);

));

我有一个表格, tds,我需要添加到饼图中,我遍历每一行并推入值。注意:因为饼图只有1个系列,所以我使用chartoptions.series [0] .data。


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.

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?

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:

$.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 2 This is the format that the chart is pulling from - very simple, category name and value with \n after each.

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

解决方案

EDIT: The response down below is more correct!

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

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

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:

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();.

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.

这篇关于通过JSON与Highcharts重新载入海图数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆