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

1 javascript php ajax jquery highcharts

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

我编写了一个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);
                }
            }
Run Code Online (Sandbox Code Playgroud)

我想知道我是否做错了什么以及如何在每次拉动数据时都能获得回显数据的功能.

提前致谢!

Bla*_*nzo 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在你的项目中,创建一个php文件(在本例中为get_server_cpu_usage.php),它返回get_server_cpu_usage()的结果;