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

时间:2015-02-11 23:01:57

标签: javascript php jquery ajax highcharts

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

我编写了一个PHP函数,每次运行函数时都会得到当前的加载数据;我们称之为get_server_cpu_usage()

我的JS代码应该每秒使用JS来提取这些数据,以便为图形提供数据,但是出于某种原因,似乎每秒都没有提取数据,而我只得到一个值,导致实时图表为flatline。

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

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

提前致谢!

1 个答案:

答案 0 :(得分:5)

你无法使用这样的javascript运行php-code客户端。你需要的是一个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()的结果;