PHP 代码只在 javascript setInterval 中运行一次 [英] PHP code only runs once inside javascript setInterval

查看:34
本文介绍了PHP 代码只在 javascript setInterval 中运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 JC 课程中学习 PHP 和 Javascript.我有以下学校项目.下面的 setInterval() 每 3 秒运行一次,但是嵌入的 PHP 代码只运行第一次.

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.

newVal 第一次更新,但在接下来的迭代中不会改变它的值.该脚本永远不会通过 telnet 回到服务器以查找值是否已更改.

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

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

推荐答案

基本上,当您在 javascript 中编写 php 代码时,它总是在页面加载时运行一次.之后你只是写php代码到浏览器根本看不懂(Php在服务器端处理,输出的是Html、Css和Javascript,浏览器可以解释)

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)

因此,如果您需要在不重新加载页面的情况下从服务器更新数据,唯一的方法是使用 Ajax 请求,它基本上连接到页面内的服务器并从中获取数据.

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 的更多信息:Ajax 基础知识

more on Ajax: Ajax Basics

这篇关于PHP 代码只在 javascript setInterval 中运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆