1

我正在尝试使用 MySQL、PHP 和 jquery 让 jquery flot 简单线图工作。
我只得到一个没有绘制点或线的空白图表。据我所知,代码中的一切都应该是正确的,但我想看看我缺少什么。

请参阅下面的代码。感谢帮助!

<html>
<head>

<style type="text/css">
body { font-family: Verdana, Arial, sans-serif; font-size: 12px; }
#placeholder { width: 450px; height: 200px; }
</style>


<script type="text/javascript" language="javascript" src="../js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="../flot/jquery.flot.js"></script>

</head>
<body>

$lineqry = 

"SELECT
dsmp.metric_date,
dsmp.metric_value
FROM applications.daily_scorecard_metric_performance dsmp

$lres = mysql_query ($lineqry,$prod);
$lrow = mysql_fetch_array($lres);

   while($lrow = mysql_fetch_assoc($lres)) 
 {
    $lineset[] = array($lrow['metric_date'],$lrow['metric_value']);
}
?>


<script type="text/javascript">
var plotdata = <?php echo json_encode($lineset);?>;

$(function () {
$.plot($("#placeholder"), [ plotdata ]);
});
</script>

<div id="placeholder"></div>

</body>
</html>

$lineresult这是PHP中数组的示例输出:

array(9) { [0]=> array(2) { [0]=> string(10) "2013-09-30" [1]=> string(1) "0" } [1]=> array(2) { [0]=> string(10) "2013-10-01" [1]=> string(3) "423" } [2]=> array(2) { [0]=> string(10) "2013-10-02" [1]=> string(3) "404" } [3]=> array(2) { [0]=> string(10) "2013-10-03" [1]=> string(3) "428" } [4]=> array(2) { [0]=> string(10) "2013-10-04" [1]=> string(3) "353" } [5]=> array(2) { [0]=> string(10) "2013-10-05" [1]=> string(3) "190" } [6]=> array(2) { [0]=> string(10) "2013-10-06" [1]=> string(3) "315" } [7]=> array(2) { [0]=> string(10) "2013-10-07" [1]=> string(3) "531" } [8]=> array(2) { [0]=> string(10) "2013-10-08" [1]=> string(3) "520" } } 

这是 json_encode 的输出:

[["2013-09-30","0"],["2013-10-01","423"],["2013-10-02","404"],["2013-10-03","428"],["2013-10-04","353"],["2013-10-05","190"],["2013-10-06","315"],["2013-10-07","531"],["2013-10-08","520"]] 
4

2 回答 2

2

文档看来,该插件不支持将数据作为字符串,还要生成一个时间序列,您需要使用时间戳并包含时间插件:jquery.flot.time.js.

添加该 js 文件并对 PHP 代码进行以下更改以提供正确的数据:

$lineset[] = array(strtotime($lrow['metric_date']) * 1000, (int) $lrow['metric_value']);
于 2013-10-10T06:24:02.213 回答
2

要扩展Koala_dev的答案,您需要将额外的选项传递到$.plot()对象中才能正确识别时间跨度。

/**
 *  Creates for json:
 *  [[13805000000, 0],[138080600000, 423].. etc
**/
$lineset[] = array(
               strtotime($lrow['metric_date']) * 1000, 
               (int) $lrow['metric_value']
             );

这将打印沿 x 轴的时间戳;然后要转换为实际可读的日期格式,您需要在调用时将其与您的选项一起添加$.plot()

在此处输入图像描述

/**
 *  Flot Options,
 *  Modify the timestamps with:
 *  %Y - Year, %m - Month, %d - Day
**/
var opts = { 
    xaxis: {
        mode: "time",
        timeformat: "%Y/%m/%d"
    }
};

if ( typeof $.fn.plot !== 'undefined' ) {
     $.plot( $("#placeholder"), [ plotdata ], opts );
}

然后最终生成下面带有可读 x 轴的正确图表:

在此处输入图像描述

于 2013-10-10T07:25:25.863 回答