Google图表多次绘制相同的图表

时间:2016-01-25 16:34:49

标签: php ajax charts modal-dialog

我正在尝试在html中创建一个模态对话框,并在按下某些内容时在模式中绘制一个谷歌图表。

function inter(id)
{
var arr = [['Album','Vizualizari']];
$.ajax({

url: 'popular.php',
type: 'GET',
dataType: 'json',
success: function (json) {
    $.each(json,function (i ,value )
    {
      var c =[value.title, value.popular];
      arr.push(c);
    });

google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);

  function drawStuff() {
    google.visualization
    var data = new google.visualization.arrayToDataTable(arr);

    var options = {
      title: 'Chess opening moves',
      width: 800,
      legend: { position: 'none' },
      bars: 'vertical', // Required for Material Bar Charts.
      axes: {
        y: {
          0: { side: 'top', label: 'Percentage'} // Top x-axis.
        }
      },
      bar: { groupWidth: "100%" }
    };

    var chart = new google.charts.Bar(document.getElementById('top_x_div'));
    chart.draw(data, options);
  };
}});
}

它起作用但仅限于第一模态。当我尝试打开另一个模态时,我得到了以下错误:google.charts.load() cannot be called more than once。如何使用另一个回调绘制图表,而不是'setOnLoadCallback'?

1 个答案:

答案 0 :(得分:0)

您的问题是您的功能包含以下两行:

google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);

这是错误的。当{API}加载完成后,google.charts.load()会加载Google可视化API,setOnLoadCallback()会执行一次。但是,您不希望在加载Google可视化时显示图表,但是当用户单击按钮(或其他)以显示模式时。因此,请完全删除setOnLoadCallback并将load()移至全局范围 - 只需从drawStuff()处理程序手动调用success

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

function inter(id) {
    var arr = [
        ['Album', 'Vizualizari']
    ];
    $.ajax({
        url: 'popular.php',
        type: 'GET',
        dataType: 'json',
        success: function(json) {
            $.each(json, function(i, value) {
                var c = [value.title, value.popular];
                arr.push(c);
            });
            drawStuff(arr);
        })
    })

    function drawStuff(arr) {
        var data = new google.visualization.arrayToDataTable(arr);
        var options = {
            title: 'Chess opening moves',
            width: 800,
            legend: {
                position: 'none'
            },
            bars: 'vertical', // Required for Material Bar Charts.
            axes: {
                y: {
                    0: {
                        side: 'top',
                        label: 'Percentage'
                    } // Top x-axis.
                }
            },
            bar: {
                groupWidth: "100%"
            }
        };

        var chart = new google.charts.Bar(document.getElementById('top_x_div'));
        chart.draw(data, options);
    }
}