尝试通过(jQuery)ajax调用加载Google图表

Trying to load Google charts through a (jQuery)ajax call

本文关键字:调用 ajax 加载 Google 图表 jQuery      更新时间:2023-09-26

可能重复:
尝试通过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都不会在我的原始页面中运行,这就是为什么图表没有显示的原因。

我想问各位大师:有没有办法从query.php中显示图表。或者有没有办法在用户投票后显示图表(包括用户提交的数据(?我还能采取什么其他方法?

虽然我对JavaScript/JQuery不是很流利,但我可能能够遵循你们提供的任何代码(甚至伪代码,任何一点都有帮助!(。

使您的按钮默认禁用

在js文件中加载Google API,加载回调启用您的按钮

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

将drawChart函数移到js文件中,添加一个参数"rows">

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

在php文件内部构建所需的行并返回它们(作为有效的json(

在btn点击发布数据时,在成功回调时调用drawChart函数并将返回的行传递给它

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


或者,如果您不想禁用该按钮,您可以在成功后首先加载google API和加载回调调用drawChart并传递响应//函数(({drawChart(响应(;}