如何确定Google Visualization是否已加载

12
我正在一些网页中展示谷歌图表。但我不能保证我的客户能够访问谷歌:客户端计算机将与我的Web服务器在同一个局域网中(可以访问谷歌),但我不能保证所有客户端都能够访问局域网之外的网络。
我想向那些能够访问谷歌的客户展示数据,并向那些不能访问的客户展示普通的HTML表格。
我尝试将一个变量设置为false,并在Google Visualization API加载时调用的方法中将其更改为true:
var canAccessGoogleVisualizationVar = false;
google.load('visualization', '1', {packages: ['corechart'], callback: canAccessGoogleVisualization});
function canAccessGoogleVisualization() 
{
    canAccessGoogleVisualizationVar = true;
}

但它似乎不起作用。

如何从客户端知道Google可视化是否可访问?


更新:上面的代码没有起作用,因为以下代码(我之前没有发布,因为我认为它没有意义):

google.setOnLoadCallback(drawVisualization);

function drawVisualization() 
{
    // Check if Google Visualization is loaded
    if (!canAccessGoogleVisualizationVar) {
        alert('Can't access Google Visualization');
    }

    // The following code can be any of the samples from Google (see http://code.google.com/apis/ajax/playground/?type=visualization#pie_chart).
    var data = new google.visualization.DataTable();
    // Add columns and values to data
    ...
    // Call new google.visualization.AnyChartBuilderFromTheAPI(<element>).draw(data);
}

我注意到我的代码没有起作用,因为如果canAccessGoogleVisualizationVar == true,则不会执行if分支,如果它是false,则function drawVisualization()也不会被执行。
所以我将if测试移到函数外面:
google.setOnLoadCallback(drawVisualization);

function drawVisualization() 
{
    // Any drawVisualization unchanged from the samples from Google (see http://code.google.com/apis/ajax/playground/?type=visualization#pie_chart).
}

// Check if Google Visualization is loaded at the end of this <script> </script>
if (!canAccessGoogleVisualizationVar) {
    alert('Can't access Google Visualization');
}
</script>

但现在它不起作用了,因为评估if (!canAccessGoogleVisualizationVar)在调用方法canAccessGoogleVisualization()的行google.load(?, ?, canAccessGoogleVisualization);之前被执行。
我如何确保在尝试执行调用google.load(...);后读取canAccessGoogleVisualizationVar的值?

更新了问题并提供了更多信息。 - J.A.I.L.
值得注意的是,您可以将 gviz js 和 css 复制出来,并从内部应用程序所在的位置提供服务。许多图表都是在客户端完成的,因此以这种方式可以很好地工作(我已经这样做了)。只需查看正常加载 api 时发送的网络调用,即可看到所需的文件。需要注意的是,a)代码将被压缩,b)如果不手动更改,您将无法获取代码更新,但这可能是一种选项 :) - oli
谢谢@peter,我会尝试一下。如果我不手动更改代码,它不会被更新的事实是一个优点(在这种情况下)。 - J.A.I.L.
抱歉...我在上一条评论中提到的是@oli,而不是(@)peter。 - J.A.I.L.
4
注意,将 Google 的 JS 本地化提供违反了服务条款。 - EKW
1个回答

17

您可以尝试

function canAccessGoogleVisualization() 
{
    if ((typeof google === 'undefined') || (typeof google.visualization === 'undefined')) {
       return false;
    }
    else{
     return true;
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接