chart.js停止通过API调用在图表上显示条形图

时间:2019-03-22 17:49:32

标签: javascript api chart.js

这是可行的,但是当我刷新页面时,它退出了工作。当我将data: / lables:更改为普通数组时,它可以正常工作。我怀疑API调用有问题,但是当我将调用的值记录到控制台时,正在按预期填充数组。刷新页面后,有人可以帮忙解释一下,如果看到的东西不合适会导致其停止工作?

<!DOCTYPE html>
<html>

<head>
  <title>Add multiple layers | CARTO</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta charset="UTF-8">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.7.2/dist/Chart.bundle.min.js"></script>
  <script src="https://cartodb-libs.global.ssl.fastly.net/carto.js/v4.0.0-beta.10/carto.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>

  <style>
    #container {
      position: absolute;
            bottom: 200px;
            left: 150px;
            width: 1410px;
      height: 100px;
            padding: 0 15px;
    }
  </style>
</head>

<body>
  <canvas id="myChart" width="400" height="400"></canvas>

  <script>
    // var CARTO_QUERY = https://acctname.carto.com/api/v2/sql?q=SELECT * FROM ticketspercounty_copy LIMIT 100&api_key=key&format=geojson;
    var request = new XMLHttpRequest()
    const countyList = [];
    const ticketCounts = [];

    request.open('GET', 'https://acctname.carto.com/api/v2/sql?q=SELECT * FROM ticketspercounty_copy LIMIT 100&api_key=key', true)
    request.onload = function() {
      // Begin accessing JSON data here
      var data = JSON.parse(this.response)

      if (request.status >= 200 && request.status < 400) {
        // console.log(data.rows);
        data.rows.forEach(element => {
          countyList.push(element.countycounty);
          ticketCounts.push(element.ticketcount);
          // console.log(element.countycounty + ' has ' + element.ticketcount + ' tickets');
        })
      } else {
        console.log('error')
      }
    };

    request.send();

    console.log(countyList);
    console.log(ticketCounts);
    var ctx = document.getElementById('myChart').getContext('2d')
    var myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: countyList,
        datasets: [{
          label: '# of tickets',
          data: ticketCounts,
          borderWidth: 1
        }]
      },
      options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
      // options: options
    });

  </script>
</body>

</html>

api的示例输出是:

countyList['richland','darlington','kershaw']
ticketCounts[100,75,100]

0 个答案:

没有答案