简体   繁体   English

在Ajax上加载Google图表-成功

[英]Loading Google Chart on Ajax — success

I'm populating Google Chart from an ajax, but it's works only when the ajax's load is fast enough. 我正在从ajax填充Google图表,但是只有在ajax的加载速度足够快的情况下,它才有效。

And too, i need to keep my data as variable to be used later on re-sizes function and other data managment. 同样,我还需要将数据保留为变量,以便以后在调整大小功能和其他数据管理中使用。

I'm working with the Google chart's tutorial at the moment. 目前,我正在使用Google图表的教程。

I just added some consoles.log to see where it's fails. 我只是添加了一些consoles.log来查看失败的地方。

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

     function drawChart(dataIN) {
      console.log(dataIN);
      if(dataIN == undefined){
        console.log("opt 1")
        console.log(dataIN);
          var jsonData = $.ajax({
            url: "getData.php",
            dataType: "text",
            async: false
              }).responseText;
      }else{
        console.log("opt 2");
        console.log(dataIN);
      }

      // Create our data table out of JSON data loaded from server.
      console.log("data in process")
      var data = new google.visualization.DataTable(dataIN);

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

var GAdata = $.ajax({
        url: "getData.php",
        data: "test",
        async: false,
        success: function(resultData){
            google.setOnLoadCallback(drawChart(resultData));
            return resultData;
        }
    }).responseText;
    </script>

the last console log is "data in process". 最后一个控制台日志是“正在处理数据”。

Any ideas? 有任何想法吗?

Your setOnLoadCallback is backwards. 您的setOnLoadCallback是向后的。 setOnLoadCallback means that the chart component is ready, so you can solve it in 2 ways: setOnLoadCallback表示图表组件已准备就绪,因此您可以通过两种方式解决它:

  1.  google.setOnLoadCallback(function() { $.ajax({ url: "getData.php", data: "test", success: function(resultData) { drawChart(resultData); return resultData; } }); }; 

Or 要么

  1. Have both run async, and if setOnLoadCallback returns before your Ajax result, you do nothing, you make drawChart call from your ajax success, if the ajax call returns before setOnLoadCallback then you store the result in a variable then call drawChart from setOnLoadCallback passing the cached result 都运行异步,并且如果setOnLoadCallback在Ajax结果之前返回,则不执行任何操作,则从ajax成功执行drawChart调用,如果ajax调用在setOnLoadCallback之前返回,则将结果存储在变量中,然后从setOnLoadCallback调用drawChart并传递缓存结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM