0

我创建了 API 来从 MySQL 中提取数据。我想要做的是将 API 的响应(输出)连接到 Google Chart。问题是图表不显示 API 响应。知道我会怎么做吗?

这是我的代码:

// api connection
var request = new XMLHttpRequest()
request.open('POST', 'http://localhost:3000/api', true)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

var obj
request.onreadystatechange = function() {
    // check api status
    if (this.readyState == 4 && this.status == 200) {

        // response
        obj = JSON.parse(this.responseText)
    }

    // google chart
    google.charts.load("current", {packages:["corechart"]})
    google.charts.setOnLoadCallback(pieChart)

    // piechart function
    function pieChart() {

        // push response
        var pieData = []
        obj.forEach(item => {
            pieData.push([item.title, item.data)]
        })

        // add response to chart
        var data = new google.visualization.DataTable()
        data.addColumn('string', 'Title')
        data.addColumn('string', 'Size')
        data.addRows(pieData)

        var options = {
            title: '',
            is#D: true
        }

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d')
        chart.draw(data, options)
    }
}

谢谢你。

4

1 回答 1

0
function pieChart() {
  $.ajax({
    url: 'http://localhost:3000/graph',
    type: 'post',
    dataType: 'json',
    crossDomain: true,
    success: function(jsonObj) {
      var arr = [
        ['Road Type', 'Size']
      ];
      $.each(jsonObj, function(i, tObj) {
        console.log(tObj)

        arr.push([String(tObj.title), parseFloat(tObj.data)]);

      });
      console.log(arr);
      var data = google.visualization.arrayToDataTable(arr);

      var options = {
        title: '',
        is3D: true
      };

      var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
      chart.draw(data, options);
    }
  });
}

来源:http: //jsfiddle.net/K8bk3

于 2020-08-15T17:13:32.913 回答