小编典典

每次Ajax调用后重新绘制Google图表

ajax

当图表第一次使用初始默认Ajax答复加载时,它可以正常工作。如果我添加console.log(chart_data),我会看到默认数据,然后在提交后我会看到新数据。唯一的问题是图表不会再次绘制。我知道drawChart函数不会第二次运行,我只是不知道为什么。我假设是的话,图表将重绘。抱歉,答案很明显。我对jQuery
/ Ajax非常陌生。

var chart_data;
var startdate = "default";
var enddate = "default";

function load_page_data(){
    $.ajax({
        url: 'get_data.php',
        data: {'startdate':startdate,'enddate':enddate},
        async: false,
        success: function(data){
            if(data){
                chart_data = $.parseJSON(data);
                google.load("visualization", "1", {packages:["corechart"]});
                google.setOnLoadCallback(function(){ drawChart(chart_data, "My Chart", "Data") })
            }
        },
    });
}

load_page_data();

function drawChart(chart_data, chart1_main_title, chart1_vaxis_title) {
    var chart1_data = new google.visualization.DataTable(chart_data);
    var chart1_options = {
        title: chart1_main_title,
        vAxis: {title: chart1_vaxis_title,  titleTextStyle: {color: 'red'}}
    };

    var chart1_chart = new google.visualization.BarChart(document.getElementById('chart1_div'));
    chart1_chart.draw(chart1_data, chart1_options);
}

任何帮助,将不胜感激。谢谢!


阅读 262

收藏
2020-07-26

共1个答案

小编典典

您只需要在页面中执行一次google.load。您正在加载数据的事实使事情变得有些复杂,但并没有太多。我建议您在javascript顶部执行一次google.load,并将load_page_data设置为回调。然后,您将从那里调用drawChart。修改后的代码如下所示:

var chart_data;
var startdate = "default";
var enddate = "default";
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(load_page_data);

function load_page_data(){
    $.ajax({
        url: 'get_data.php',
        data: {'startdate':startdate,'enddate':enddate},
        async: false,
        success: function(data){
            if(data){
                chart_data = $.parseJSON(data);
                drawChart(chart_data, "My Chart", "Data");
            }
        },
    });
}

function drawChart(chart_data, chart1_main_title, chart1_vaxis_title) {
    var chart1_data = new google.visualization.DataTable(chart_data);
    var chart1_options = {
        title: chart1_main_title,
        vAxis: {title: chart1_vaxis_title,  titleTextStyle: {color: 'red'}}
    };

    var chart1_chart = new google.visualization.BarChart(document.getElementById('chart1_div'));
    chart1_chart.draw(chart1_data, chart1_options);
}
2020-07-26