在php页面中创建jqplot图

时间:2011-12-08 01:02:16

标签: php javascript ajax jqplot

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

1 个答案:

答案 0 :(得分:4)

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

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

    <?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 docs的粗略检查,如果你编辑你从中链接的javascript第12行:

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

    对此:

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

    您的函数应该在'chartdiv'id元素中渲染图。似乎$ .jqplot函数的第一个参数是创建它的元素......