如何动态设置日期范围变量并重绘Google图表?

时间:2013-04-07 22:24:27

标签: php javascript google-api google-visualization redraw

我使用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>

1 个答案:

答案 0 :(得分:7)

好吧,如果我正确理解你,那么你在设计和设计这些操作的哪些部分是服务器端(PHP)以及哪些部分是客户端(Javascript)以及客户端 - 服务器通信策略时遇到困难。这是一个常见的speedbump。有几种方法可以解决它。

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

// 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. 只有在您发回的数据是json编码块时,Ajax才会起作用,这意味着您的图表构建数据需要在启动任何 HTML输出,包括您的页面模板。如果你不能把图表构建代码放在脚本的顶部,那么你必须将它添加到一个完整的单独脚本中,它所做的就是计算图表的数据,然后你可以让它返回ajax数据没有页面上的所有其他HTML。如果你不能做其中任何一件事,你只需要关闭Ajax位并进行整页刷新。


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