在highchart中绘制JSON结果

时间:2018-11-02 15:29:43

标签: javascript json highcharts

我将此代码用于highchart和JSON处理:

Exception.printStackTrace()
var json;
var quantity = [];
var nm = [];
$(document).ready(function () {
  $.ajax({
    url: "../Broken/index.php",
    dataType: "text",
    success: function (data) {
      json = $.parseJSON(data);
      console.log(json);


      for (var i = 0; i < json.length; i++) {
        var obj = json[i];
        for (var prop in obj) {
          if (obj.hasOwnProperty(prop) && obj[prop] !== null && !isNaN(obj[prop])) {
            obj[prop] = +obj[prop];
          }
        }
      }

      console.log(JSON.stringify(json, null, 2));

      console.log(json);

      for (var j in json) {
        quantity.push(json[j].OC)
      }

      console.log(quantity);

    },
  });

});


var chart = new Highcharts.Chart({
  chart: {
    renderTo: 'container',
    type: 'column',
    options3d: {
      enabled: true,
      alpha: 15,
      beta: 15,
      depth: 50,
      viewDistance: 25
    }
  },
  title: {
    text: 'Broken OC weekly trend'
  },
  plotOptions: {
    column: {
      depth: 25
    }
  },
  series: [{
    data: quantity
  }]
});

这是index.php JSON结果:

<!DOCTYPE html>
<html>
  <head>
    <title>Broken OC graph</title>
    <script src="../Broken/jquery.min.js"></script>
    <script src="../Broken/highcharts.js"></script>
    <script src="../Broken/highcharts-3d.js"></script>
  </head>
  <body>
    <br /><br />
    <div style="width:900px;">
      <div id="container" style="width: 900px; height: 500px;"></div>
    </div>
  </body>
</html>

我的问题是: 如何用higchart绘制变量[ {"wk": "W30", "OC": "7"}, {"wk": "W31", "OC": "4"}, {"wk": "W32", "OC": "2"}, {"wk": "W33", "OC": "4"}, {"wk": "W34", "OC": "2"}, {"wk": "W35", "OC": "4"}, {"wk": "W36", "OC": "2"} ] ? 如果我将该变量插入quantity字段中,则不会发生任何事情。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

$.ajax是异步的:http://api.jquery.com/jquery.ajax/,因此您将创建一个具有空数据数组的图表。您应该在数据准备就绪时创建图表:

function getData() {
    var json = [
  {"wk": "W30", "OC": "7"}, 
  {"wk": "W31", "OC": "4"}, 
  {"wk": "W32", "OC": "2"},
  {"wk": "W33", "OC": "4"},
  {"wk": "W34", "OC": "2"},
  {"wk": "W35", "OC": "4"},
  {"wk": "W36", "OC": "2"}
]

    var quantity = [];

    for (var i = 0; i < json.length; i++) {
        var obj = json[i];
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop) && obj[prop] !== null && !isNaN(obj[prop])) {
                obj[prop] = +obj[prop];
            }
        }
    }


    for (var j in json) {
        quantity.push(json[j].OC)
    }

    createChart(quantity);
}

function createChart(quantity) {
    Highcharts.chart('container', {
        series: [{
            data: quantity
        }]
    });
}

getData();

实时演示:http://jsfiddle.net/BlackLabel/b1jecy4t/