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


How to pull PHP function every second in JS/Ajax

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

我已经编写了一个PHP函数,每次运行该函数时都会获得当前的加载数据;让我们称之为CCD_ 1。

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

JS,调用PHP函数:

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);
                }
            }

我想知道我是否做错了什么,以及如何让函数在每次提取数据时都对其进行响应。

提前感谢!

您不能使用这样的javascript在客户端运行php代码。您需要的是一个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),返回get_server-cpu_usage()的结果;