如何在 JS/Ajax 中每秒拉取 PHP 函数

How to pull PHP function every second in JS/Ajax

我正在使用 Highcharts(参见:http://www.highcharts.com/demo/dynamic-update)API 动态更新图表以反映我的网络面板上的服务器负载。

我编写了一个 PHP 函数,每次函数 运行 时都会获取当前负载数据;让我们称之为 get_server_cpu_usage().

我的 JS 代码应该使用 JS 每秒提取一次数据,以便为图形提供数据,但是由于某种原因,数据似乎不是每秒提取一次,我只得到一个值,导致实时图表变平。

正在调用 PHP 函数的 JS:

events: {
                load: function () {

                    // set up the updating of the chart each second
                    var series = this.series[0];
                    setInterval(function () {
                        var x = (new Date()).getTime(), // current time
                            y = <?php echo get_server_cpu_usage(); ?>;
                        series.addPoint([x, y], true, true);
                    }, 1000);
                }
            }

我想知道我是否做错了什么,以及如何让函数在每次拉取数据时回显数据。

提前致谢!

您不能 运行 php 那样使用 javascript 对客户端进行编码。您需要的是 ajax 调用来提取数据。例如通过使用 jQuery.

    events: {
    load: function () {

        // set up the updating of the chart each second
        var series = this.series[0];
        setInterval(function () {
            $.get(
                'get_server_cpu_usage.php',
                function(result) {
                    var x = (new Date()).getTime(), // current time
                        y = result;
                    series.addPoint([x, y], true, true);
                }
            )
        }, 1000);
    }
}

在您的项目中,创建一个 php 文件(在本例中为 get_server_cpu_usage.php),其中 returns get_server_cpu_usage();

的结果