使用 setInterval 和 jQuery load 在 JS 数组中加载 PHP


Loading PHP inside JS array using setInterval and jQuery load

下面的代码使用地图显示饼图。它运行良好,但我需要使用 PHP 动态放置生成的数据 (abcdata(,然后使用 setInterval 每 5 秒刷新一次数据。数据未显示在索引中.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"]
    });
}

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

您可以使用 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);