简体   繁体   English

PHP代码只在javascript setInterval中运行一次

[英]PHP code only runs once inside javascript setInterval

I'm just learning PHP and Javascript in a JC class. 我只是在JC课上学习PHP和Javascript。 I have the following for a school project. 我有一个学校项目的以下内容。 The following setInterval() runs every 3 seconds, however the embedded PHP code only runs the first time. 以下setInterval()每3秒运行一次,但嵌入式PHP代码仅在第一次运行。

ie newVal gets updated the first time but doesn't change it's value on the following iterations. newVal第一次更新,但在下面的迭代中不会改变它的值。 The script never telnets back into the server to find if the value changed. 该脚本从不telnet回到服务器以查找值是否更改。

 setInterval(function () {
    var newVal, mem;

    <?php $telnet = new PHPTelnet();?>;
    <?php $result = $telnet->Connect('ip_address','username','password');?>;
    <?php   $telnet->DoCommand('show process memory summary"', $result);?>;
    <?php $result = preg_replace('/[\r\n ]+/',' ', trim($result)); ?>;

    newVal = "<?php echo substr($result,61,7) ?>"; 
    newVal = newVal / 10000;

    mem.update(newVal);
  }, 3000);

Thanks to some of the answers/comments below, this is what I did to make it work: 感谢下面的一些答案/评论,这就是我做的工作:

Javascript 使用Javascript

     setInterval(function () {
        $.get("memAccess.php", function(return_value) {
                mem.update(parseFloat(return_value));
        });
    }, 3000);

Separate PHP file 单独的PHP文件

<?php
    $telnet = new PHPTelnet();
    $result = $telnet->Connect('ip_address','username','password');

    $telnet->DoCommand('show process memory summary', $result);
    $result = preg_replace('/[\r\n ]+/',' ', trim($result));
    $result = substr($result,61,7);

    echo $result; 
    $telnet->Disconnect();
    exit();
?>

Basically when you write php code inside javascript, it always run once, when the page is loaded. 基本上当你在javascript中编写php代码时,它总是在页面加载时运行一次。 After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret) 在此之后你只是将php代码写入浏览器,这根本就是不明白(Php是在服务器上处理的,输出是Html,Css和Javascript,浏览器可以解释)

So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it. 因此,如果您需要从服务器更新数据而不重新加载页面,那么执行此操作的唯一方法是使用Ajax请求,它基本上连接到页面内的服务器并从中获取数据。

more on Ajax: Ajax Basics 更多关于Ajax: Ajax Basics

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM