0

下面的代码使用浮动图显示一个饼图。它工作得很好,但我需要使用 PHP 动态放置生成的数据(abcdata),然后使用 setInterval 每 5 秒刷新一次数据。数据未显示在 index.php 中,饼图消失。我相信它与通过 jQuery 加载的 var abdata 变量有关,但我不知道如何解决它。

我的意图是通过 PHP 加载数据(abdata)并每隔几秒刷新一次数据。

// Code in index.php 

setInterval(function() {

    $(".test").load("test.php");

}, 1000); 


// Code in the test.php file: 

var abdata = [
  { label: "B",  data: 90}, // The data values are queried using PHP and SQL
  { label: "C",  data: 112},
  { label: "A",  data: 112}
];

if($("#chart").length)
{
    $.plot($("#chart"), abdata,
    {
            series: {
                    pie: {
                            innerRadius: 0.5,
                            show: true
                    }
            },
            legend: {
                show: false
            },
            colors: ["#f29020","#434343", "#3fbed3"]
    });
}

如果有人能提供帮助,我将不胜感激!提前致谢!

4

1 回答 1

1

您可以使用 ajax() 将 abdata 值作为 json 返回,然后使用该值,而不是使用 load() 加载数据。

// Code in index.php 

setInterval(function() {
    $.ajax({
        type:"GET",
        url:"test.php",
        success:function(response) {
            var abdata = $.parseJSON(response);
            if($("#chart").length)
            {
                $.plot($("#chart"), abdata,
                {
                        series: {
                            pie: {
                                innerRadius: 0.5,
                                show: true
                            }
                        },
                        legend: {
                            show: false
                        },
                        colors: ["#f29020","#434343", "#3fbed3"]
                });
            }          
        }
    });
}, 1000); 


// Code in the test.php file: 

$abdata = array(
  array( 'label'=> "B",  'data'=> 90), // The data values are queried using PHP and SQL
  array( 'label'=> "C",  'data'=> 112),
  array( 'label'=> "A",  'data'=> 112)
);
echo json_encode($abdata);
于 2013-10-13T05:43:55.420 回答