繁体   English   中英

highcharts不确定如何从外部json加载数据

[英]highcharts not sure how to load data from external json

我无法以任何方式导入JSON,因为我是JS的新手,所以可能是一个非常愚蠢的问题。 无论如何,我的完整代码来自一个示例:

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Highcharts Example</title> <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script type="text/javascript"> $(function() { var chart; $(document).ready(function() { $.getJSON("data.php", function(json) { chart = new Highcharts.Chart({ chart: { renderTo: 'container', type: 'line', marginRight: 130, marginBottom: 25 }, title: { text: 'Revenue vs. Overhead', x: -20 //center }, subtitle: { text: '', x: -20 }, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, yAxis: { title: { text: 'Amount' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, tooltip: { formatter: function() { return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + this.y; } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0 }, series: json }); }); }); }); </script> </head> <body> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/modules/exporting.js"></script> <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div> </body> </html> 

如果data.php的格式如以下示例所示,则可以正常工作: [{ "name": "Revenue", "data": [23987, 24784, 25899, 25569, 25897, 25668, 24114, 23899, 24987, 25111, 25899, 23221] }, { "name": "Overhead", "data": [21990, 22365, 21987, 22369, 22558, 22987, 23521, 23003, 22756, 23112, 22987, 22897] }]但是,我是通过执行SQL查询通过json_encode创建JSON,因此我的data.php实际上是这样的: [{"id":"1","time":"12.00"},{"id":"2","time":"13.00"}]

但是,我通过进行SQL查询通过json_encode创建JSON,因此我的data.php实际上是这样的:

[{"id":"1","time":"12.00"},{"id":"2","time":"13.00"}]

基本上,我需要Y轴为“ id”,x轴为“ time”。

我已经尝试了很多次,但是我什至无法加载图表。 是我的JSON完全格式化的方式还是有使其工作的方式?

谢谢!

我建议创建一个格式化函数以将您的数据转换为预期的格式:

const format = (arr) => {
  let ids = arr.map((item) => {
    return Number(item.id);
  });
  let times = arr.map((item) => {
    return item.time;
  });
  return {
      ids,
      times
  };
}

例如:

let data = [{"id":"1","time":"12.00"},{"id":"2","time":"13.00"}];
let json = format(data);
// json = {ids: [Array of IDs], times: [Array of times]}

然后,您可以使用json数据通过Highcharts.Chart传递:

...
xAxis: {
  categories: json.times
},
...
series: [{name: 'IDs', data: json.ids}]

我已经测试过,并得到以下内容:

在此处输入图片说明

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM