我正在使用 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>
为清楚起见编辑:
不要忘记使用第一个(页面刷新)示例中的以下代码块,否则您根本就没有在使用表单:
$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)));
只有当您发送回的唯一数据是 json 编码 block 时,Ajax 才会起作用,这意味着您的图表构建数据需要位于脚本的顶部,然后才能任何 HTML 输出已启动,包括您的页面模板。如果您不能将图表构建代码放在脚本的顶部,那么您必须将它添加到一个完整的单独脚本中,它所做的只是计算图表的数据,然后您可以让它返回ajax 数据,页面上没有所有其他 HTML。如果您不能执行其中任何一项操作,则只需关闭 Ajax 位并刷新整个页面。
编辑 2:我添加了 data-ajaxaction属性为 <form>元素,这是我为 ajax 提供不同操作而编写的用户定义属性。我还更改了 $.ajax()调用以使用此属性而不是 action属性。
关于php - 如何动态设置日期范围变量并重绘 Google 图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868566/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/