jQuery 使用 AJAX 加载 Google Visualization API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2315250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery load Google Visualization API with AJAX
提问by Arturo
There is an issue that I cannot solve, I've been looking a lot in the internet but found nothing.
有一个我无法解决的问题,我在互联网上查了很多,但一无所获。
I have this JavaScript that is used to do an Ajax request by PHP. When the request is done, it calls a function that uses the Google Visualization API to draw an annotatedtimeline to present the data.
我有这个用于通过 PHP 执行 Ajax 请求的 JavaScript。请求完成后,它会调用一个函数,该函数使用 Google Visualization API 绘制带注释的时间线来呈现数据。
The script works great without AJAX, if I do everything inline it works great, but when I try to do it with AJAX it doesn't work!!!
该脚本在没有 AJAX 的情况下运行良好,如果我内联执行所有操作,则它运行良好,但是当我尝试使用 AJAX 执行时,它不起作用!!!
The error that I get is in the declaration of the "data" DataTable, in the Google Chrome Developer Tools I get a Uncaught TypeError: Cannot read property 'DataTable' of undefined
.
我得到的错误是在“数据”DataTable 的声明中,在 Google Chrome 开发者工具中我得到了一个Uncaught TypeError: Cannot read property 'DataTable' of undefined
.
When the script gets to the error, everything on the page is cleared, it just shows a blank page.
当脚本遇到错误时,页面上的所有内容都被清除,它只显示一个空白页面。
So I don't know how to make it work.
所以我不知道如何让它工作。
$(document).ready(function(){
// Get TIER1Tickets
$("#divTendency").addClass("loading");
$.ajax({
type: "POST",
url: "getTIER1Tickets.php",
data: "",
success: function(html){
// Succesful, load visualization API and send data
google.load('visualization', '1', {'packages': ['annotatedtimeline']});
google.setOnLoadCallback(drawData(html));
}
});
});
function drawData(response){
$("#divTendency").removeClass("loading");
// Data comes from PHP like: <CSV ticket count for each day>*<CSV dates for ticket counts>*<total number of days counted>
// So it has to be split first by * then by ,
var dataArray = response.split("*");
var dataTickets = dataArray[0];
var dataDates = dataArray[1];
var dataCount = dataArray[2];
// The comma separation now splits the ticket counts and the dates
var dataTicketArray = dataTickets.split(",");
var dataDatesArray = dataDates.split(",");
// Visualization data
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Tickets');
data.addRows(dataCount);
var dateSplit = new Array();
for(var i = 0 ; i < dataCount ; i++){
// Separating the data because must be entered as "new Date(YYYY,M,D)"
dateSplit = dataDatesArray[i].split("-");
data.setValue(i, 0, new Date(dateSplit[2],dateSplit[1],dateSplit[0]));
data.setValue(i, 1, parseInt(dataTicketArray[i]));
}
var annotatedtimeline = new google.visualization.AnnotatedTimeLine(document.getElementById('divTendency'));
annotatedtimeline.draw(data, {displayAnnotations: true});
}
回答by jamie-wilson
I remember when I used a Google API it explicitly said to initialize the load first off. So maybe keep the google.load function out of the AJAX, and then just keep calling the second part of your function on success:
我记得当我使用 Google API 时,它明确说要首先初始化负载。因此,也许将 google.load 函数保留在 AJAX 之外,然后在成功时继续调用函数的第二部分:
//Straight Away!
google.load('visualization', '1', {'packages': ['annotatedtimeline']});
$(document).ready(function(){
// Get TIER1Tickets
$("#divTendency").addClass("loading");
$.ajax({
type: "POST",
url: "getTIER1Tickets.php",
data: "",
success: function(html){
// Succesful, load visualization API and send data
google.setOnLoadCallback(drawData(html));
}
});
});
回答by daxiang28
I know this is an older post, but after some digging through the google.load docs, I found an async option in case you want to dynamically load the libs:
我知道这是一篇较旧的帖子,但是在对 google.load 文档进行了一些挖掘之后,我发现了一个异步选项,以防您想动态加载库:
http://code.google.com/apis/loader/
http://code.google.com/apis/loader/
function loadMaps() {
google.load("visualization", "2", {"callback" : function(){ alert(4); }});
}
回答by balazs
I know this is an old thread but this might help others.
I've run into the same problem now and it is very similar (if not the same) I had earlier with a CMS:
我知道这是一个旧线程,但这可能对其他人有所帮助。
我现在遇到了同样的问题,它与我之前使用 CMS 时遇到的非常相似(如果不一样):
code on page:
页面代码:
<div id='targetdiv'></div>
<script type="text/javascript">
$(document).ready( function () {
$('#targetdiv').load('...some url...');
});
</script>
part of the script loaded with ajax:
用ajax加载的脚本的一部分:
<script type="text/javascript">
document.write("hello");
</script>
The result is a page with the text "hello" that looks like it is still being loaded. This is caused by the document.write method. Since the script is loaded into an already finished and closed document, the browser opens a new one and I suppose the javascript engine is waiting for the next line of code that will never arrive as opening a new document deleted the one being executed.
结果是一个带有文本“hello”的页面,看起来它仍在加载中。这是由 document.write 方法引起的。由于脚本已加载到已完成且已关闭的文档中,因此浏览器会打开一个新文档,我想 javascript 引擎正在等待下一行代码,该代码永远不会到达,因为打开新文档会删除正在执行的文档。
回答by Finbarr
This is a bit of a shot in the dark:
这是在黑暗中的一个镜头:
google.setOnLoadCallback(function() {
drawData(html)
});
google.setOnLoadCallback(function() {
drawData(html)
});
It may be that the reference to html is lost, and a closure is required.
可能是html的引用丢失了,需要关闭。
回答by Darkyo
Could you provide a sample of the data returned ? You may call directly drawData(html) :
你能提供一个返回数据的样本吗?您可以直接调用 drawData(html) :
$.ajax({
type: "POST",
async: false,
url: "getTIER1Tickets.php",
data: "",
success: function(html){
// Succesful, load visualization API and send data
google.load('visualization', '1', {'packages': ['annotatedtimeline']});
//You are already in a callback function, better like this ?
drawData(html);
}});
回答by dan
I am using an AJAX-based tab system and Google's Interactive Line Chart Visualizations in one of my projects and ran into a similar brick wall.
我在我的一个项目中使用了基于 AJAX 的选项卡系统和 Google 的交互式折线图可视化,但遇到了类似的砖墙。
Because of AJAX's inherent blocking of cross-domain scripting, you can't load the Google javascript API (http://www.google.com/jsapi) or any other external resources.
由于 AJAX 对跨域脚本的固有阻塞,您无法加载 Google javascript API ( http://www.google.com/jsapi) 或任何其他外部资源。
And since Google's terms of service prohibit offline (aka "not hosted on Google") use of their visualization API, you can't legally get a copy of the scripts and host them yourself as is required.
而且由于 Google 的服务条款禁止离线(也称为“不在 Google 上托管”)使用其可视化 API,因此您无法合法获取脚本副本并根据需要自行托管它们。
I tried a hacky workaround of including a file called "get_vis.php" instead of the "visualization_page.php" in my tabs; where the contents of "get_vis.php" is:
我尝试了一种 hacky 解决方法,在我的选项卡中包含一个名为“get_vis.php”的文件而不是“visualization_page.php”;“get_vis.php”的内容在哪里:
<?php
echo file_get_contents('http://domain.com/path/to/visualization_page.php');
?>
But, no luck, it seems the only way to get the API to load properly is to adjust security settings so as to allow interaction with Google's servers. I don't know if it helps, but good luck.
但是,不幸的是,让 API 正确加载的唯一方法似乎是调整安全设置以允许与 Google 的服务器进行交互。我不知道它是否有帮助,但祝你好运。
回答by James
Have you tried doing this as a synchronous AJAX request? Notice the asyncsetting below.
您是否尝试将其作为同步 AJAX 请求执行?注意下面的异步设置。
$.ajax({
type: "POST",
async: false,
url: "getTIER1Tickets.php",
data: "",
success: function(html){
// Succesful, load visualization API and send data
google.load('visualization', '1', {'packages': ['annotatedtimeline']});
google.setOnLoadCallback(drawData(html));
}
});
回答by dimvic
i am not familiar at all with the google apis, but i guess that 'html' in the callback is actually json or script, you can try the $.ajax 'dataType' option:
我对 google apis 一点都不熟悉,但我猜回调中的 'html' 实际上是 json 或脚本,您可以尝试 $.ajax 'dataType' 选项:
$.ajax({
type: "POST",
url: "getTIER1Tickets.php",
dataType: "json",//"script"
data: "",
success: function(html){
// Succesful, load visualization API and send data
google.load('visualization', '1', {'packages': ['annotatedtimeline']});
google.setOnLoadCallback(drawData(html));
}
});
more info: http://api.jquery.com/jQuery.ajax/
回答by acrosman
Looks like you're missing the Google library that provides the visualization. Are you sure you've included all the needed google scripts?
看起来您缺少提供可视化的 Google 库。你确定你已经包含了所有需要的谷歌脚本吗?
回答by user123456
This works for me
这对我有用
google.load("visualization", "1", { packages: ["corechart"] });
var chart ;
var data ;
var options;
function Change(s)
{
// s in json format
google.setOnLoadCallback(reDraw(s));
function reDraw(s) {
console.log(new Function("return " + s)().length); // to test if json is right
data = google.visualization.arrayToDataTable(new Function("return "+s)());
options = {
title: 'Product Scanes',
vAxis: { title: '', titleTextStyle: { color: 'red'} }
};
}
chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
function requestDate() // cal the method when you want to draw the chart
{
$.ajax({
type: "POST", // CHANGED
// contentType: "application/json; charset=utf-8",
url: "something.php",
data: { parameters you wanna pass },
success: function (d) {
Change(d);
}
});
}
}