【问题标题】:How do I set a date range variable dynamically and redraw a Google chart?如何动态设置日期范围变量并重绘 Google 图表?
【发布时间】:2013-04-07 22:24:27
【问题描述】:

我正在使用 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 将检索数据。函数 #2 将调用数据检索函数并绘制图表。当您单击按钮/更改下拉菜单时,它应该调用一个处理函数,该函数将获取适当的数据并将其发送到图表绘制函数。基本上,取代码的前半部分(drawChart() 之前)并将其转换为接受 $end 参数的函数。您是否已经尝试过类似的方法?

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


【解决方案1】:

好的,如果我的理解正确,那么您在构思和设计这些操作的哪些部分是服务器端 (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'])&amp;&amp;$_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 仅在您发送回的 only 数据是 json 编码块时才有效,这意味着您的图表构建数据需要在 任何 HTML 输出已启动,包括您的页面模板。如果你不能将图表构建代码放在脚本的顶部,那么你必须将它添加到一个完整的单独脚本中,它所做的只是计算图表的数据,然后你可以让它返回ajax 数据没有页面上的所有其他 HTML。如果你不能做这些事情,你只需要关闭 Ajax 位并刷新整个页面。


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

【讨论】:

  • 谢谢。是的,你正确地理解了我,是的,我更喜欢 AJAX 方法。我已经安装了 jQuery。我已经在页面上包含了您的代码,但是当单击“重绘图表”按钮时,我被重定向到显示我的主页的 URL http://www.finance.nickputman.com/?ajax=0&amp;range=%2B1+year&amp;action=Redraw+Chart,而不是具有以下 URL 的当前页面:@987654331 @。任何想法为什么会发生这种情况?
  • 好的,首先,在表单标签中将action="&lt;?= $_SERVER['PHP_SELF']; ?&gt;"更改为action="&lt;?= $_SERVER['PHP_SELF']; ?&gt;?&lt;?= $_SERVER['QUERY_STRING']; ?&gt;"。这将使您保持page_id=174,并修复应该让表单工作,只需刷新页面即可。其次,看起来它没有执行任何 jQuery onsubmit 事件。在 javascript 控制台中查找会阻止 javascript 执行的错误(如果您使用的是 Chrome,请按 f12 并点击“控制台”选项卡)。在preventDefault()之前,放上alert('debug');,看看能不能运行。
  • 谢谢。 jQuery 错误是 'Semantic Issue - Expected token ')' 在这一行:url: $(this).attr('action'),。表单操作的 URL 字符串仍然存在问题。通过您建议的修改,我仍然被重定向到主页。如果我在 URL 中省略了 &lt;?= $_SERVER['PHP_SELF']; ?&gt;?,那么 URL 是正确的,除了包含问号,即 http://www.finance.nickputman.com/page_id=174?ajax=0&amp;range=%2B3+months&amp;action=Redraw+Chart
  • ajax 参数周围缺少花括号。此外,我没有将查询字符串添加到“action”表单中,而是添加了一个块来创建隐藏输入以供它们通过。更新了已编辑答案中的代码。除非你有一些奇怪的 mod_rewrite 规则,否则没有 PHP_SELF 的 URL 将无法工作,因为你需要在 page_id=174 之前的 ?。这就是新的隐藏输入块的用途。
  • 谢谢,页面加载时 jQuery 冲突已经消失,但是现在当我单击重绘图表按钮时,什么也没有发生 - 即 URL 没有更新。相反,几秒钟后,我在控制台中收到以下错误:format+en,default,core chart.l.js - Other Issue - Error: Table has no columns. 似乎存在与您的脚本与 Google API 通信的方式有关的问题。
猜你喜欢
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2013-09-23
相关资源
最近更新 更多