在php页面中创建jqplot图形


Creating jqplot graph in php page

我试图通过使用apache服务器做一个小项目来学习php。我有一个php页面,我想显示一个条形图与jqplot使用数据我从MySql查询拉。我已经有一个查询工作给我我想要的数据。问题是我不知道如何实现这到一个jqplot图。我猜我需要做一个ajax调用,但如果我能避免,我想。到目前为止,我的PHP页面代码在这里http://snipt.org/oknnl2。这个柱状图的javascript代码在这里http://snipt.org/oknoi3.
我希望图表呈现在第177行上的div id=chartdiv。我要把6个图表形象化。如果我能得到一些帮助,我相信我可以用同样的过程来构建其他的。

PHP不能创建javascript图并将其发送到下游的客户端,但是您也不必在加载页面后进行实际的AJAX调用。简单的javascript一旦页面加载就足够了。如果在PHP级别检索所需的数据,则可以在客户端接收到的HTML中使javascript可以使用这些数据。实现这一点的步骤:

  1. 首先,使用PHP从MySQL数据库中检索所需的数据。
  2. 然后,在javascript中输出使用PHP检索到的绘图数据代码块作为PHP发送给客户端的HTML的一部分
  3. 在页面加载时执行带有PHP种子数据的javascript。

那么,一个简单的例子:

<?php
// Retrieve plot data from mysql
$q = '...';
$r = mysql_query($q);
$plot_row1 = array();
$plot_row2 = array();
$plot_row3 = array();
while ($row = mysql_fetch_array($r)) {
    // append values to $plot_row1, $plot_row2 and $plot_row3 arrays
}
$my_page_title = 'My first PHP/JS Combo Foray';
?>
<html>
<head>
    <script type="text/javascript" src="/scripts/jquery-1.5.2.min.js"></script>
    <script type="text/javascript" src="/scripts/my_plotter.js"></script>
</head>
<body>
<h1><?php echo $my_page_title; ?></h1>
<div id="chartdiv">
    Hold on, javascript is loading the plot ...
</div>
</body>
</html>

<script type="text/javascript">
$(document).ready(function() {
    // we're combining the php array elements into a comma separated list
    // so that when the code is output javascript thinks it's an array.
    // if the $plot_row1 = array(1, 2, 3) then we'd get this:
    // 
    // row1 = [1, 2, 3];
    // 
    // if you needed quotes around the imploded php array values (if they
    // are strings where javascript is concerned) you could do this instead:
    // 
    // row1 = ["<?php echo substr(implode('","', $plot_row1), 0, -2); ?>"];
    row1 = [ <?php echo rtrim(implode(',', $plot_row1), ','); ?> ];
    row2 = [ <?php echo rtrim(implode(',', $plot_row2), ','); ?> ];
    row3 = [ <?php echo rtrim(implode(',', $plot_row3), ','); ?> ];
    // call your js function that creates the plot
    showBrittleness(row1,row2,row3);
    // add whatever js code you need to append the plot to $('#chartdiv')
}
</script>

根据对jqplot文档的粗略检查,如果您编辑javascript的第12行,您将从以下链接:

var plot1 = $.jqplot('chart1', [s1, s2], {

:

var plot1 = $.jqplot('chartdiv', [s1, s2], {

您的函数应该在'chartdiv' id元素中呈现绘图。它似乎是$的第一个参数。Jqplot函数是用来创建它的元素…