【问题标题】:Loading Google Chart Api using Ajax in html page在 html 页面中使用 Ajax 加载 Google Chart Api
【发布时间】:2012-09-26 08:07:23
【问题描述】:

我正在使用 Ajax 代码加载 html 页面

例如:

  $.ajax({
  url: 'Context.html',
  dataType: 'html',
  timeout: 500, 
  success: function(html) {
  $("div#mainbody").html(html);
  }
  });

Context.html 我正在将它加载到其他一些 html 页面中,比如 Home.html

但我在 Context.html 中使用谷歌 API 生成饼图

生成饼图的代码,即在 Context.html 中是

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
 google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Count'],
      ['2005',  70],
      ['2006',  80],
      ['2007',  140],
      ['2008',  220],
      ['2009',  290],
      ['2010',  400],
      ['2011',  500]
    ]);

    var options = {
      title: 'Head Count-(Apple Year)',
      colors:['#129212']              
      };
 var chart = new google.visualization.ColumnChart(document.getElementById('jsf_headcount_bargraph'));
   chart.draw(data, options);
    }
  </script> 

当我在 Home.html 页面中加载 Context.html 时,在 Home.html 中加载 Context.html 后找不到饼图

我尝试给 ALERT("");在我为饼图编写代码的脚本中。我收到警报消息,所以 Ajax 正在执行 javascript,但我没有得到相同脚本的饼图。所以我被困在 Home.html 页面中加载饼图

【问题讨论】:

  • 替代方案:在同一页面上绘制图表并保持隐藏直到不需要。或者您可以使用图像饼图。希望这会奏效。
  • 我也有同样的问题,怎么办?
  • Context.html 的唯一目的是绘制图表,还是还有其他用途? div "jsf_headcount_bargraph" 是在您的主页中还是在 context.html 中?

标签: html ajax google-visualization


【解决方案1】:

如果你像这样制作 Context.html

<script>
var j = 20;
alert();
</script>

然后我确实收到了警报(使用 $.ajax({success: function() {} }) 等)。

[示例]

function execAjax() {
    $.ajax( {
        url: 'index2.html',
        success: function( html ) {
            $("#content").html( html );

            checkJSvalue();
        },
        error: function() {
            alert( "Error" );
        }
    });
}

function checkJSvalue() {

    alert( j );
}

示例 HTML (index2.html)

<div>
content of index2.html
</div>
<script>
var j = 20;
alert();
</script>

我试图做的是将代码直接放在“home.html”中,但我已经遇到了错误。无论如何,您应该颠倒绘图函数的使用和声明顺序。

// Bad
// google.setOnLoadCallback(drawChart);
// function drawChart() {}

// Good
function drawChart() {}
google.setOnLoadCallback(drawChart);


除此之外,我已经从 google.jsapi.js 得到了这个错误(复制到本地)

Uncaught Error: Container is not defined format+nl,default,corechart.I.js:841

所以那里出了点问题,这不是实际问题的一部分,它被缩小了等等,所以我不会去那里。

希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    如果我替换代码一切正常

    google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);
    

    内联

    google.load('visualization', '1.0', {'packages':['corechart'], "callback": drawChart});
    

    【讨论】:

      猜你喜欢
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 2015-04-23
      • 2015-03-31
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多