jQuery 使用 AJAX 加载 Google 可视化 API

发布于 2024-08-22 17:50:39 字数 2402 浏览 4 评论 0原文

有一个问题我无法解决,我在网上查了很多,但一无所获。

我有这个 JavaScript,用于通过 PHP 执行 Ajax 请求。请求完成后,它会调用一个函数,该函数使用 Google Visualization API 绘制带注释的时间线来呈现数据。

该脚本在没有 AJAX 的情况下工作得很好,如果我内联执行所有操作,它工作得很好,但是当我尝试使用 AJAX 执行它时,它不起作用!

我得到的错误是在“数据”DataTable 的声明中,在 Google Chrome 开发者工具中,我得到一个未捕获的类型错误:无法读取未定义的属性“DataTable”

当脚本出现错误时,页面上的所有内容都会被清除,只显示一个空白页面。

所以我不知道如何让它发挥作用。

$(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});                              
}

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.

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!!!

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.

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});                              
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

半城柳色半声笛 2024-08-29 17:50:39

我记得当我使用 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)); 
        }
    });  
});

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:

//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)); 
        }
    });  
});
寂寞笑我太脆弱 2024-08-29 17:50:39

我知道这是一篇较旧的文章,但在深入研究 google.load 文档后,我发现了一个异步选项,以防您想动态加载库:

http://code.google.com/apis/loader/

function loadMaps() {
   google.load("visualization", "2", {"callback" : function(){ alert(4); }});
}

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:

http://code.google.com/apis/loader/

function loadMaps() {
   google.load("visualization", "2", {"callback" : function(){ alert(4); }});
}
猫腻 2024-08-29 17:50:39

我知道这是一个旧线程,但这可能对其他人有帮助。
我现在遇到了同样的问题,它与我之前使用 CMS 时遇到的非常相似(如果不一样):

页面上的代码:

<div id='targetdiv'></div>
<script type="text/javascript">
$(document).ready( function () {
   $('#targetdiv').load('...some url...');
});
</script>

使用 ajax 加载的脚本的一部分:

<script type="text/javascript">
  document.write("hello");
</script>

结果是一个带有文本“hello”的页面看起来它仍在加载中。
这是由 document.write 方法引起的。由于脚本被加载到一个已经完成并关闭的文档中,浏览器会打开一个新文档,我想 javascript 引擎正在等待下一行代码,当打开一个新文档删除正在执行的文档时,该代码永远不会到达。

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:

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:

<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.

一身仙ぐ女味 2024-08-29 17:50:39

这有点盲目:

google.setOnLoadCallback(function() {
绘制数据(html)
});

可能是html的引用丢失了,需要闭包。

This is a bit of a shot in the dark:

google.setOnLoadCallback(function() {
drawData(html)
});

It may be that the reference to html is lost, and a closure is required.

旧梦荧光笔 2024-08-29 17:50:39

您能否提供返回数据的样本?
您可以直接调用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);                                                   
}}); 

Could you provide a sample of the data returned ?
You may call directly 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);                                                   
}}); 
水水月牙 2024-08-29 17:50:39

您是否尝试过将其作为同步 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));                                                   
    }
}); 

Have you tried doing this as a synchronous AJAX request? Notice the async setting below.

$.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));                                                   
    }
}); 
东风软 2024-08-29 17:50:39

我对 google api 一点也不熟悉,但我猜回调中的 '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));                                                   
    }
});

更多信息: http://api.jquery.com/jQuery.ajax/

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:

$.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/

(り薆情海 2024-08-29 17:50:39

看来您缺少提供可视化的 Google 库。您确定已经包含了所有需要的谷歌脚本吗?

Looks like you're missing the Google library that provides the visualization. Are you sure you've included all the needed google scripts?

夜无邪 2024-08-29 17:50:39

我在我的一个项目中使用基于 AJAX 的选项卡系统和 Google 的交互式折线图可视化,并遇到了类似的砖墙。

由于 AJAX 固有地阻止跨域脚本,因此您无法加载 Google javascript API (http://www .google.com/jsapi)或任何其他外部资源。

由于 Google 的服务条款禁止离线(也称为“不在 Google 上托管”)使用其可视化 API,因此您无法合法获取脚本的副本并根据需要自行托管它们。

我尝试了一种巧妙的解决方法,在我的选项卡中包含一个名为“get_vis.php”的文件,而不是“visualization_page.php”;其中“get_vis.php”的内容是:

<?php 
echo file_get_contents('http://domain.com/path/to/visualization_page.php');
?>

但是,不幸的是,似乎让 API 正确加载的唯一方法是调整安全设置,以便允许与 Google 服务器交互。我不知道这是否有帮助,但祝你好运。

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.

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.

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.

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:

<?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.

月寒剑心 2024-08-29 17:50:39

这对我有用

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);


                }
            });    
        }
}

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);


                }
            });    
        }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文