PHP code only runs once inside javascript setInter

2020-05-05 19:23发布

问题:

I'm just learning PHP and Javascript in a JC class. 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.

i.e. newVal gets updated the first time but doesn't change it's value on the following iterations. The script never telnets back into the server to find if the value changed.

 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

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

Separate PHP file

<?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();
?>

回答1:

Basically when you write php code inside javascript, it always run once, when the page is loaded. 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)

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.

more on Ajax: Ajax Basics