【问题标题】:Run google visualisation (javascript) loaded via ajax运行通过 ajax 加载的谷歌可视化(javascript)
【发布时间】:2012-04-21 23:58:06
【问题描述】:

长期聆听者,第一次来电者。不是很擅长ajax。大概我在这里做了一些非常密集的事情:

尝试运行从 ajax 响应返回的带有 html 的 google 可视化,但即使我可以在 firebug 的 xhr 响应中看到代码,从 ajax 页面加载时它也不会运行。

直接访问response2.php?var=X就可以完美运行了,所以想必输出的代码本身没有问题。

(我已经在 ajax 页面的标题和 response2.php 之间移动了 jsapi 和 google.load(visualization),但都没有成功)

ajax 调用

$.ajaxSetup ({
    cache: false
});

$.ajax ({
    type: "GET",
    url: "return2.php",
    data: "council=Leeds City Council",
    dataType: "html",
    success: function (responseText) { 
      document.getElementById('result').innerHTML = responseText;
    }
});

return2.php

<?php
$docKey = "0Aqk6sC3LBlfjdHUxRDIycjlSM3NvX0JCWnhxUjRUbFE";
$docQuery = $_GET['council'];
?>
<script type="text/javascript">
function drawVisualization() {
google.visualization.drawChart({
   "containerId": "councilViz",
   "dataSourceUrl": "http://spreadsheets.google.com/a/google.com/tq?key=<?php echo   $docKey; ?>",
   "query":"SELECT A,B,C WHERE A CONTAINS '<?php echo $docQuery; ?>'",
   "chartType": "Table",
   "options": {
      "width": 560,
      "height" : 200
   }
 });
}
google.setOnLoadCallback(drawVisualization);
</script>
<div id="councilViz">
<?php echo $docQuery; ?>
</div>

response2.php 获取 GET 变量,运行 google 电子表格 api 查询并返回以下代码:

ajax 响应

<script type="text/javascript">
  function drawVisualization() {
    google.visualization.drawChart({
   "containerId": "councilViz",
   "dataSourceUrl": "http://spreadsheets.google.com/a/google.com/tq?key=0Aqk6sC3LBlfjdHUxRDIycjlSM3NvX0JCWnhxUjRUbFE",
   "query":"SELECT A,B,C WHERE A CONTAINS 'Leeds City Council'",
   "chartType": "Table",
   "options": {
      "width": 560,
      "height" : 200
   }
 });
  }
  google.setOnLoadCallback(drawVisualization);
</script>
<div id="councilViz">
Leeds City Council</div>

尽我所能,当代码被ajax调用时,我无法绘制表格。我可以看到结果,但可视化脚本中什么也没有。

非常感谢,

一个

【问题讨论】:

    标签: ajax jquery google-visualization


    【解决方案1】:

    您需要创建 div 以将返回的 html 插入其中,使用 .innerHTML 将您的 html 插入该 div。

    然后使用 .appendChild 将 div 附加到 dom 中的目标。

    通过设置元素的 innerHTML 属性添加的脚本不会被执行。

    函数 addScript(responseText) { var newdiv = document.createElement('div'); newdiv.innerHTML = 响应文本; document.getElementById('target').appendChild(newdiv); }

    【讨论】:

    • 杰森,感谢您的回答。我应该指出 ajax 页面确实包含一个用于放置代码的 div (#result),如下所示:
    • 是的,用结果交换目标并在响应时运行 addScript 函数。
    猜你喜欢
    • 2011-06-11
    • 1970-01-01
    • 2013-02-26
    • 2015-08-22
    • 2013-05-16
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多