使用jQuery .load()将Google Visualization页面加载到div中

时间:2011-07-16 22:13:36

标签: jquery ajax google-visualization

我有一个显示Google可视化图表的页面:

page1.html

<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = new google.visualization.DataTable();
    // Added data

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, {width: 900, height: 400});
  }
</script>

我还有第二页:

page2.html

<div id="container">

</div>

来自page2.html我想用这个:

$('#container').load("page1.html");

但是,这不起作用。我所期待的。我的问题是:这有可能实现吗?你可以使用ajax加载到div,这是一个包含Google Charts生成的图表的页面吗?

干杯!

2 个答案:

答案 0 :(得分:1)

输入代码在第1页上编写此脚本以动态加载API

<script type="text/javascript">
        var chartLoaded = false;
        function loadAPI()
        {            
            var script = document.createElement("script");
            script.src = "http://www.google.com/jsapi?callback=loadChart";
            script.type = "text/javascript";
            document.getElementsByTagName("head")[0].appendChild(script);
        }

        function loadChart() 
        {
            google.load("visualization", "1", { packages: ["corechart"], "callback": loaded });
        }

        function loaded() 
        {
            chartLoaded = true;
           //alert('loaded. Now you can load the chart');
            drawChart();
        }

        function drawChart() 
        {
            if (!chartLoaded) 
            {
                alert('chart api not loaded yet.');
                return;
            }
            else 
                alert('chart api has loaded.');

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

            data.addColumn('string', 'Years');
            data.addColumn('number', 'sales');

            data.addColumn('number', 'Expenses');

            data.addRows([
                                ['2004', 1000, 400],
                                ['2006', 2500, 100],
                                ]);

            var options = {
                title: 'Company Performance',
                vAxis: { title: 'Year', titleTextStyle: { color: 'red'} }
            };

            var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>

在第1页的就绪功能上,调用方法loadAPI();

答案 1 :(得分:0)

不,你不能只将整页加载到你的div中。我建议将脚本解压缩到自己的文件中,然后调用函数生成图形。 So..first

 function loadChart(element) {
     google.load("visualization", "1", {packages:["corechart"]});
     google.setOnLoadCallback( function() {
          var data = new google.visualization.DataTable();
          // Added data

          var chart = new google.visualization.LineChart(document.getElementById(element));
          chart.draw(data, {width: 900, height: 400});
     });
 }

然后,您只需拨打loadChart(element),即可指定图表的去向。这样您就可以在任何页面上绘制图形,例如

loadChart('#container');

确保在标题中包含您的js文件!

祝你好运:)