无法在JSFiddle上创建图表

时间:2019-01-16 04:01:18

标签: javascript jquery ajax jsfiddle canvasjs

我正在尝试通过Javascript在JsFiddle上创建图表。 这是我的代码。

$(document).ready(function() {
  var dataPointsA = []
  var dataPointsB = []

  $.ajax({
    type: 'GET',
    url: 'https://api.myjson.com/bins/12qook',
    dataType: 'json',
    success: function(field) {
      for (var i = 0; i < field.length; i++) {
        dataPointsA.push({
          x: field[i].userId,
          y: field[i].numberOfusers
        });
      }

      var chart = new CanvasJS.Chart("chartContainer", {
        title: {
          text: "User Count"
        },

        data: [{
          type: "line",
          name: "line1",
          dataPoints: dataPointsA
        }]
      });

      chart.render();
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

但是当我按下Run时,它仅显示以下内容: After run

我对此并不陌生,所以您能告诉我我的代码有什么问题吗?谢谢

1 个答案:

答案 0 :(得分:2)

如果要呈现分类数据,请通过将type更改为column,将x更改为label,使用条形图而不是折线图:

$.ajax({
  type: 'GET',
  url: 'https://api.myjson.com/bins/12qook',
  dataType: 'json',
  success(data) {
    new CanvasJS.Chart("chartContainer", {
      title: {
        text: "User Count"
      },
      data: [{
        type: "column",
        dataPoints: data.map(
          ({ userId, numberOfusers }) => ({ label: userId, y: numberOfusers })
        )
      }]
    }).render();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>