Creating Pie Chart with Google Charts API from JSON

混江龙づ霸主 提交于 2019-12-02 04:07:40

问题


right now I´m trying to create a pie chart from a JSON Output from my MySQL Database. I am quite new to JavaScript thats why I ask you for some help. I found the following project and changed it a little bit. But now my problem is that I have 81 different values to be added in my pie chart, but if I try to add more data in data.addRow() I receive an error that there is more data than expected. What can I do to load all rows for my pie chart?

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
 var data;
 var chart;

  // Load the Visualization API and the piechart package.
  google.charts.load('current', {'packages':['corechart']});

  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

  // Callback that creates and populates a data table,
  // instantiates the pie chart, passes in the data and
  // draws it.
  function drawChart() {


    var jsonData = $.ajax({
                    url: "FetchDate.php",
                    dataType:"json",
                    async: false
                    }).done(function (results) {

      var data = new google.visualization.DataTable();

      data.addColumn('string', 'VoteName');
      data.addColumn('number', 'VoteCount');

      $.each(results, function (i, row) {
        var strData = "vt".concat(i);
        data.addRow([
          strData,
          parseFloat(row.vt0)
        ]);
      });
  });

    // Set chart options
    var options = {'title':'My Pie Chart',
                   'width':600,
                   'height':600};

    // Instantiate and draw our chart, passing in some options.
    chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    google.visualization.events.addListener(chart, 'select', selectHandler);
    chart.draw(data, options);
  }

  function selectHandler() {
    var selectedItem = chart.getSelection()[0];
    var value = data.getValue(selectedItem.row, 0);
    alert('The user selected ' + value);
  }

</script>

And my JSON Output:

[{"id":"1","name":"improvisiertester Unterricht","vt0":"0","vt1":"0","vt2":"0","vt3":"0","vt4":"1","vt5":"0","vt6":"0","vt7":"0","vt8":"0","vt9":"0","vt10":"0","vt11":"0","vt12":"0","vt13":"0","vt14":"0","vt15":"0","vt16":"0","vt17":"0","vt18":"0","vt19":"0","vt20":"0","vt21":"0","vt22":"0","vt23":"0","vt24":"0","vt25":"0","vt26":"0","vt27":"0","vt28":"3","vt29":"2","vt30":"0","vt31":"12","vt32":"0","vt33":"0","vt34":"0","vt35":"1","vt36":"0","vt37":"0","vt38":"0","vt39":"0","vt40":"1","vt41":"2","vt42":"0","vt43":"0","vt44":"1","vt45":"0","vt46":"1","vt47":"0","vt48":"0","vt49":"0","vt50":"0","vt51":"0","vt52":"0","vt53":"0","vt54":"0","vt55":"0","vt56":"0","vt57":"0","vt58":"1","vt59":"0","vt60":"1","vt61":"0","vt62":"0","vt63":"0","vt64":"0","vt65":"0","vt66":"0","vt67":"0","vt68":"0","vt69":"0","vt70":"0","vt71":"0","vt72":"0","vt73":"0","vt74":"0","vt75":"0","vt76":"0","vt77":"0","vt78":"0","vt79":"0","vt80":"0","vt81":"0","alreadyVoted":",66,78,30,67,39,37,79,75,81,32,11,3,56,18,28,46,16,6,17,9,35,64,58,68,41"}]

Explination: id is the specific id from my question name is the question vt1-81 are the possible answers and how often somebody voted alreadyVoted stores all Users Ids who voted

Thank you for your time and work!!!


回答1:


The JSON from the post contains an array with one element, which has multiple keys...

So rather than iterate the elements with $.each, use Object.keys...

See following working example...

var data;
var chart;

google.charts.load('current', {
  callback: drawChart,
  packages:['corechart']
});

function drawChart() {
  var results = [{"id":"1","name":"improvisiertester Unterricht","vt0":"0","vt1":"0","vt2":"0","vt3":"0","vt4":"1","vt5":"0","vt6":"0","vt7":"0","vt8":"0","vt9":"0","vt10":"0","vt11":"0","vt12":"0","vt13":"0","vt14":"0","vt15":"0","vt16":"0","vt17":"0","vt18":"0","vt19":"0","vt20":"0","vt21":"0","vt22":"0","vt23":"0","vt24":"0","vt25":"0","vt26":"0","vt27":"0","vt28":"3","vt29":"2","vt30":"0","vt31":"12","vt32":"0","vt33":"0","vt34":"0","vt35":"1","vt36":"0","vt37":"0","vt38":"0","vt39":"0","vt40":"1","vt41":"2","vt42":"0","vt43":"0","vt44":"1","vt45":"0","vt46":"1","vt47":"0","vt48":"0","vt49":"0","vt50":"0","vt51":"0","vt52":"0","vt53":"0","vt54":"0","vt55":"0","vt56":"0","vt57":"0","vt58":"1","vt59":"0","vt60":"1","vt61":"0","vt62":"0","vt63":"0","vt64":"0","vt65":"0","vt66":"0","vt67":"0","vt68":"0","vt69":"0","vt70":"0","vt71":"0","vt72":"0","vt73":"0","vt74":"0","vt75":"0","vt76":"0","vt77":"0","vt78":"0","vt79":"0","vt80":"0","vt81":"0","alreadyVoted":",66,78,30,67,39,37,79,75,81,32,11,3,56,18,28,46,16,6,17,9,35,64,58,68,41"}];

  data = new google.visualization.DataTable();
  data.addColumn('string', 'VoteName');
  data.addColumn('number', 'VoteCount');

  // iterate "vt" keys
  Object.keys(results[0]).forEach(function (key) {
    if (key.indexOf("vt") > -1) {
      data.addRow([
        key,
        parseFloat(results[0][key])
      ]);
    }
  });

  var options = {
    title: 'My Pie Chart',
    width: 600,
    height: 600
  };

  chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  google.visualization.events.addListener(chart, 'select', selectHandler);
  chart.draw(data, options);
}

function selectHandler() {
  // be sure something is selected
  if (chart.getSelection().length) {
    var selectedItem = chart.getSelection()[0];
    var value = data.getValue(selectedItem.row, 0);
    alert('The user selected ' + value);
  }
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Adding the ajax call back in would look something like this...

var data;
var chart;

google.charts.load('current', {
  callback: drawChart,
  packages:['corechart']
});

function drawChart() {
  data = new google.visualization.DataTable();
  data.addColumn('string', 'VoteName');
  data.addColumn('number', 'VoteCount');

  var jsonData = $.ajax({
    url: "FetchDate.php",
    dataType:"json",
    async: false
  }).done(function (results) {
    // iterate "vt" keys
    Object.keys(results[0]).forEach(function (key) {
      if (key.indexOf("vt") > -1) {
        data.addRow([
          key,
          parseFloat(results[0][key])
        ]);
      }
    });
  });

  var options = {
    title: 'My Pie Chart',
    width: 600,
    height: 600
  };

  chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  google.visualization.events.addListener(chart, 'select', selectHandler);
  chart.draw(data, options);
}

function selectHandler() {
  // be sure something is selected
  if (chart.getSelection().length) {
    var selectedItem = chart.getSelection()[0];
    var value = data.getValue(selectedItem.row, 0);
    alert('The user selected ' + value);
  }
}


来源:https://stackoverflow.com/questions/36755108/creating-pie-chart-with-google-charts-api-from-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!