如何动态设置日期范围变量并重新绘制谷歌图表


How do I set a date range variable dynamically and redraw a Google chart?

我使用PHP来设置创建Google折线图的日期范围。对于范围内的每个日期设置一个变量($running_balance),以使用数据库中的数据在折线图上创建点。我希望能够设置变量$end,这基本上决定了日期范围,动态,但我不确定如何做到这一点,以便图表将根据这个新的范围重新绘制。我知道我可以创建一个包含drawChart();的新功能来重新绘制图表,并且我将使用三个按钮将日期范围设置为1年,3个月或1个月,但我不确定如何将所有这些放在一起。以下是我目前拥有的代码:

$begin = new DateTime(date('Y-m-d', strtotime('+1 days')));
$end = new DateTime(date('Y-m-d', strtotime('+365 days')));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ( $period as $dt ) {
$date_display = $dt->format("D j M");
.....  code to generate $running_balance .....
$temp = array();
    $temp[] = array('v' => (string) $date_display); 
    $temp[] = array('v' => (string) $running_balance);
    $temp[] = array('v' => (string) $running_balance);
    $rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
<script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
    var table = <?php echo $jsonTable; ?>;
    function drawChart() {
    var data = new google.visualization.DataTable(table);
      // Create our data table out of JSON data loaded from server.
        //  var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var formatter = new google.visualization.NumberFormat({fractionDigits:2,prefix:''u00A3'});
      formatter.format(data, 1);
      var options = {
          pointSize: 5,
          legend: 'none',
          hAxis: { showTextEvery:31 },
          series: {0:{color:'2E838F',lineWidth:2}},
          chartArea: {left:50,width:"95%",height:"80%"},
          backgroundColor: '#F7FBFC',
          height: 400
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
</script>

好吧,如果我理解正确的话,你在构思和设计这些动作的哪些部分是服务器端(PHP),哪些部分是客户端(Javascript),然后是客户端-服务器通信策略方面遇到了麻烦。这是一个常见的减速带。有几种方法可以处理它。

首先(也是不太受欢迎的),您可以创建一个表单,并使用新的日期范围重新加载整个页面:

// we're looking for '+1 year', '+3 months' or '+1 month'. if someone really
// wants to send another value here, it's not likely to be a security risk
// but know your own application and note that you might want to validate
$range = isset($_GET['range'])&&$_GET['range']?$_GET['range']:'+1 year';
$begin = new DateTime(date('Y-m-d', strtotime('+1 days')));
$end = new DateTime(date('Y-m-d', strtotime($range)));
// ... the rest of your code to build the chart.
?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="get">
    <select name="range" size="1">
        <option value="+1 year">1 year</option>
        <option value="+3 months">3 months</option>
        <option value="+1 month">1 month</option>
    </select>
    <input type="submit" name="action" value="Redraw Chart">
</form>

…这是不太受欢迎的原因,因为它会导致整个页面刷新。

如果您想避免整个页面刷新,您可以做几乎相同的事情,但使用ajax。设置几乎是相同的,只有一些小的变化:

// between building the data table and the javascript to build the chart...
$jsonTable = json_encode($table);
if (isset($_GET['ajax']) && $_GET['ajax']) {
    echo json_encode(array('table' => $table));
    exit;
}
// remainder of your code, then our new form from above
?>
<form id="redraw_chart_form" action="<?= $_SERVER['PHP_SELF']; ?>" data-ajaxaction="forecast.php" method="get">
    <? foreach ($_GET as $key => $val) { ?>
    <input type="hidden" name="<?= $key; ?>" value="<?= $val; ?>">
    <? } ?>
    <input type="hidden" name="ajax" id="redraw_chart_form_ajax" value="0">
    <select name="range" size="1">
        <option value="+1 year">1 year</option>
        <option value="+3 months">3 months</option>
        <option value="+1 month">1 month</option>
    </select>
    <input type="submit" name="action" value="Redraw Chart">
</form>
<script>
    // I'm assuming you've got jQuery installed, if not there are
    // endless tutorials on running your own ajax query
    $('#redraw_chart_form').submit(function(event) {
        event.preventDefault(); // this stops the form from processing normally
        $('#redraw_chart_form_ajax').val(1);
        $.ajax({
            url: $(this).attr('data-ajaxaction'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            complete: function() { $('#redraw_chart_form_ajax').val(0); },
            success: function(data) {
                // referring to the global table...
                table = data.table;
                drawChart();
            },
            error: function() {
                // left as an exercise for the reader, if ajax
                // fails, attempt to submit the form normally
                // with a full page refresh.
            }
        });
        return false; // if, for whatever reason, the preventDefault from above didn't prevent form processing, this will
    });
</script>

为清晰而编辑:

  1. 不要忘记使用第一个(页面刷新)示例中的以下代码块,否则您根本就没有使用表单:

    $range = isset($_GET['range'])&&$_GET['range']?$_GET['range']:'+1 year';

    $begin = new DateTime(date('Y-m-d', strtotime('+1 days')));

    $end = new DateTime(date('Y-m-d', strtotime($range)));

  2. Ajax将只工作,如果只有数据,你发回的是json编码块,这意味着你的图表构建数据需要在任何 HTML输出开始之前在脚本的顶部,包括你的页面模板。如果不能将图表构建代码放在脚本的顶部,则必须将其添加到一个完整的单独脚本中,该脚本所做的全部工作就是计算图表的数据,然后可以让它返回ajax数据,而不需要页面上的所有其他HTML。如果你不能做到这两件事,你只需要关闭Ajax位,并做一个整个页面刷新。


编辑2:我将data-ajaxaction属性添加到<form>元素,这是一个用户定义的属性,我为ajax提供了不同的操作。我还更改了$.ajax()调用,以使用此属性而不是action属性。