如何从jquery .post()函数获取响应后加载谷歌图表?

时间:2015-06-26 16:41:49

标签: javascript jquery google-visualization

我正在使用UI,用户可以选择开始日期和结束日期以检索数据。其中一些数据显示在表格中,我想显示与显示的数据相关的谷歌图表。

当用户最终选择日期时,我使用$.post()函数发送这两个变量,如下所示:

<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>

$('#button-send').click(function() {
    var url_route = "{{URL::action('Controller@general_stats_post')}}";
    var start_date=$('#start_date_i').val();
    var end_date=$('#end_date_i').val();
    var datos = {start_date: start_date, end_date:end_date,_token:_token};

单击发送按钮后,我使用$ .post()函数,该函数正常工作:

$.post(url_route, datos, function(data,status){
  if(status=='success'){
    console.log('Dates sent successfully. Now the data retrieved are: '+data);
    var response = jQuery.parseJSON(data);
    if(response.events_types.length === 0){
        console.log('events_types is empty.');
    }
    else{
    console.log('The string for google charts got is: `'+response.events_types+'`');
    /*Here goes the google chart*/

    }
  }else if(status=='error'){
    console.log('Errors found');
  }
 });//end of .post() function
}); //end of onclick button-send

events_types字符串例如是:

[['Event','Total'],['Workshop',1],['Seminar',1]]

完全适用于google's jsfiddles

所以,我一直在尝试将google图表的drawChart()函数放在{}所在的字符串events_types存在的地方,如下所示:

        $.post(url_route, datos, function(data,status){
          if(status=='success'){
            console.log('Dates sent successfully. Now the data retrieved are: '+data);
            var response = jQuery.parseJSON(data);
            if(response.events_types.length === 0){
                console.log('events_types is empty.');
            }
            else{
            console.log('The string for google charts got is: `'+response.events_types+'`');
            /*GOOGLE CHART*/
    google.setOnLoadCallback(drawChart);
    function drawChart() {
   console.log('Inside the drawChart() function');
    var data = google.visualization.arrayToDataTable(response.events_types);
    var options = {
       title: 'My test'
                };

    var chart = new google.visualization.PieChart(document.getElementById('eventos_charts'));
    chart.draw(data, options);
     }  
            /*END OF GOOGLE CHART PART*/
            }
          }else if(status=='error'){
            console.log('Errors found');
          }
         });//end of .post() function
        }); //end of onclick button-send

我已经输入了一个console.log消息让我知道drawChart()已经运行了。但是,我从来没有得到那个消息。所以这意味着drawChart()函数永远不会运行:/我被卡住了。

几乎工作 - 编辑

这是正在运行的代码......但只有在我手动定义数据字符串时,也就是说:

else{
 console.log('The data string is: `'+response.tipos_eventos+'`');
 var the_string=response.tipos_eventos;
/***** start Google charts:*******/
 //google.setOnLoadCallback(drawChart);
  function drawChart() {
    console.log('Inside the drawChart() function');
    var data = google.visualization.arrayToDataTable([['Evento','Cantidad'],['Taller',1],['Seminario',1]]);//DEFINED MANUALLY

 var options = {
   title: 'The chart'
   };
  var chart = new google.visualization.PieChart(document.getElementById('events_types'));

  chart.draw(data, options);
 }
 drawChart();//Thanks to @FABRICATOR                                

/****  END Google charts: Events types *********/                               
}

但是,如果我试图动态获取数据:

else{
 console.log('The data string is: `'+response.tipos_eventos+'`');
 var the_string=response.tipos_eventos;
/***** start Google charts:*******/
 //google.setOnLoadCallback(drawChart);
  function drawChart() {
    console.log('Inside the drawChart() function');
    var data = google.visualization.arrayToDataTable(the_string);//DEFINED DYNAMICALLY

 var options = {
   title: 'The chart'
   };
  var chart = new google.visualization.PieChart(document.getElementById('events_types'));

  chart.draw(data, options);
 }
 drawChart();//Thanks to @FABRICATOR                                

/****  END Google charts: Events types *********/                               
}

我收到以下错误:

Uncaught Error: Not an array

任何让它运作的想法?我错过了什么?

1 个答案:

答案 0 :(得分:0)

最后,我找到了最简单的解决方案。 鉴于我正在使用Laravel的ORM(Illuminate / Database),所获得的数据采用json格式。

这适用于Laravel和Slim框架。

所以我将变量直接传递给视图(在Slim中):

$app->render('home.php',[
        'myArray'=>$myArray
]);

然后,在视图内部(在这种情况下,Twig视图。它应该在刀片中类似),我得到数组并将其放在Javascript代码中的变量中:

var myArray = {{ myArray|json_encode|raw }};

然后我迭代获取每个元素并将其添加到Google图表数据数组中:

$.each(myArray,function(index, value){
            //console.log('My array has at position ' + index + ', this value: ' + value.r1);
            data.addRow([value.col1,value.col2,value.col3,value.col4]);
        });

它现在有效。