google charts not showing when called through jquery ajax

▼魔方 西西 提交于 2019-12-24 08:26:00

问题


I am trying to use google chart to show the chart.My json data is coming when I am checking through the alert option to check the data are pushed into list but overall the chart is not able to display.

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript"  src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script type="text/javascript">

    // 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);

    function drawChart() {
      var jsonData = $.ajax({
          url: "http://localhost:8080/FRA-UI/api/report19graph/all",
          dataType: "json",
          async: false
          }).responseText;

      alert(JSON.stringify(jsonData));

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, {width: 400, height: 240});
    }

    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

回答1:


in order to create the data table directly from json,
the json must be in a specific format, found here...

otherwise, the data can be loaded manually,
see following snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  $.ajax({
    url: 'http://localhost:8080/FRA-UI/api/report19graph/all',
    dataType: 'json'
  }).done(function (jsonData) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Range');
    data.addColumn('number', 'Value');

    $.each(jsonData, function (index, row) {
      data.addRow([
        row.rangeLab,
        row.rangeVal
      ]);
    });

    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, {width: 400, height: 240});
  });
});


来源:https://stackoverflow.com/questions/50794518/google-charts-not-showing-when-called-through-jquery-ajax

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