簡體   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