2011-11-17 38 views
1

可能重复:
Trying to load Google charts through a jQuery ajax call尝试通过(jQuery的)AJAX调用加载谷歌图表

我一直在这个整天,不能想办法让这个工作。我对jQuery不是很熟悉。

我在做什么:我正在尝试编写一个轮询函数,用于加载结果并在不刷新的情况下将其显示在同一页面中。

到目前为止,我有这样的jQuery代码:

$("#post_yes").click(function(){ 
    $("#result").html(ajax_load); //loads ajaxloader.gif 
    $.post( 
     "query.php", 
     {answer: "yes", poll_id: 5}, 
     function(responseText){ 
      $.getScript(scriptUrl, function(){ 
       $("#result").html(responseText); 
      });    
     }, 
     "html" 
    ); 
}); 

它应该查询query.php并插入到数据库中投票。然后我编写了query.php来返回yes和no值,然后在该页面上生成一个图表。这是类似的东西,我有:

google.load('visualization', '1.0', {'packages':['corechart']}); // Load the Visualization API and the piechart package. 
    google.setOnLoadCallback(drawChart); // Set a callback to run when the Google Visualization API is loaded. 

    function drawChart() 
    { 
     // Create the data table. 
     var data = new google.visualization.DataTable(); 
     data.addColumn('string', 'Answers'); 
     data.addColumn('number', 'Number'); 
     data.addRows([ 
      ['Yes', $yes_value], 
      ['No', $no_value], 
     ]); 

     // Set chart options 
     var options = 
     { 
      'title'    :'Do you Like my smile?', 
      'colors'   :['#f25a5a','#5aa5f2'], 
      'fontName'   :'Verdana', 

      'backgroundColor' :'#e7e7e7', 
      'chartArea'   :{left:0,top:10,width:"400",height:"400"}, 
      'is3D'    : true, 
     }; 

     var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
     chart.draw(data, options);    
    } 

使用Chrome的调试器我注意到,在query.php任何JavaScript并没有在我原来的网页运行,这就是为什么图表ISN调试页面一段时间后没有被显示。

我给你的问题大师:有没有什么办法可以显示来自query.php的图表。或者有什么方法可以在用户投票后显示图表(包括用户提交的数据)? 我还可以采取其他方法吗?

尽管我对JavaScript/JQuery不太流利,但我可能会遵循任何代码(甚至伪代码,任何一点帮助!),你们都可以。

回答

0

默认情况下禁用让您的按钮

在js文件

负荷谷歌API, 负载回调启用按钮

// Set a callback to run when the Google Visualization API is loaded.  
google.setOnLoadCallback(function(){ $("#post_yes").removeAttr('disabled'); }); 

招drawChart功能,以您的js文件,添加参数“行“

function drawChart(rows) { 
    ... 
    data.addRows(rows); 
    ... 
} 

php文件生成所需的行内并返回它们(作为有效的JSON)

上BTN点击发表您的数据,成功回调调用drawChart功能,并通过返回的行给它

$.post(
    "query.php", 
    {answer: "yes", poll_id: 5}, 
    function(response){ 
    drawChart(response); 
    } 
); 


或者如果你不想禁用成功后第一次加载按钮就可以谷歌API和加载回调调用drawChart与传递的响应//function(){drawChart(response); }

+0

我不确定你的意思是“将drawChart函数移到你的js文件中”,我正在从Google的服务器调用js。我已经把drawChart()函数放在一个单独的drawChart.js文件中,并完成了其余的修改。我仍然没有看到任何事情发生。 这是我的代码在我的主页:http://pastebin.com/x6JU5DPF 在我的drawchart.js文件中,我有这个:http://pastebin.com/KMhnM8pX 而我的PHP文件,我甚至不询问数据库,我只是吐出示例数据,看看它是否有效。这里是文件:http://pastebin.com/1EWMg6FM 编辑:上面的json是有效的根据jsonlint.com – Xecure

+0

如果你直接调用drawChart({“yes”:14,“no”:9})函数,没有Ajax电话 - 你能看到图表吗?例如点击(函数(){drawChart({“yes”:14,“no”:9});}); _ – Irishka

+0

data.addRows function google from api expect a multidimensional array,so你需要像[[“yes”,14],[“no”,9]]那样按照你以前的格式传递它 – Irishka