1

我在使用来自 PHP 的数据的 Flot 中创建饼图时遇到了一个非常奇怪的问题。

好像画错了,不知道为什么。

我的 PHP 代码(用于测试)是:

echo json_encode(
'[{ label: "Series1",  data: 10},
{ label: "Series2",  data: 3},
{ label: "Series3",  data: 9},
{ label: "Series4",  data: 7},
{ label: "Series5",  data: 8},
{ label: "Series6",  data: 17}]'
);

我的 JS 文件是:

$.ajax({
type:'GET',
dataType:"json",
url:'../phpfile.php',
success: function(data) {
    console.log(data);
    $.plot($("#piechart"),data,{
        series: {
            pie: {
                show: true
            }
        }
    });
}
});

控制台日志显示:

[{ label: "Series1",  data: 10},
{ label: "Series2",  data: 3},
{ label: "Series3",  data: 9},
{ label: "Series4",  data: 7},
{ label: "Series5",  data: 8},
{ label: "Series6",  data: 17}]

我认为这是 flot 的正确格式...

但它的图形是这样的: 饼形图

有没有人有任何想法?

4

1 回答 1

1

I believe your JSON currently is invalid, at the moment, you're trying to parse an JSON String, into a JSON String (If you get what I mean!) Currently, when I echo out from the PHP end with your echo'ed json_encode(), I'm provided with:

"[{ label: \"Series1\", data: 10},\r\n{ label: \"Series2\"]"

Furthermore, I would use PHP Arrays to encode JSON, like below:

<?php 
    $arr = array( 
        array(
            "label" => "Series1",
            "data" => 10
        ),
        array(
            "label" => "Series2",
            "data" => 3
        ),
        array(
            "label" => "Series3",
            "data" => 9
        ),
        array(
            "label" => "Series4",
            "data" => 7
        ),
        array(
            "label" => "Series5",
            "data" => 8
        ),
        array(
            "label" => "Series7",
            "data" => 17
        )
    );

    echo json_encode( $arr );
?>

PHP json_encode() does accept mixed variable types, but it's most popularly used with PHP arrays.

With the above, I'm able to construct the PIE chart successfully:

Finished Chart

于 2013-08-23T18:50:35.900 回答