dongtiao5094 2016-10-10 20:13
浏览 83
已采纳

如何在PHP中回显更新变量

Thanks for coming to try and help me solve my problem!

My problem is, I would like the display a variable on my page using PHP. This variable updates every second or so. I would like this to update on the page as the variable changes. I tried using a while loop but this just continuously prints the variable. I will warn you, I am not very PHP savvy, and you're probably going to have to explain your answer to me, A LOT. Sorry I didn't include any code samples.. I didn't really think it was needed for this question. If you would like me to provide some samples, I will though. Thanks for considering answering my question! :)

  • 写回答

2条回答 默认 最新

  • doucheng5209 2016-10-10 20:30
    关注

    You try to do something which is not so easy to implement with the basics of PHP. PHP is once generated on the server side and then gives the result to the client. (your browser). If you like to change the HTML Code dynamically you should take a look at JavaScript. This will allow you to make dynamic updates without reloading the page. (e.g. a user presses a button or a timer in your case):

    var i = 1;
    
    // update site content every second
    setInterval(function() {
    
      // get div with id example
      var myElement = document.getElementById('example');
    
      // count up by 1
      i++;
    
      // update content
      myElement.innerHTML = 'Zahl ' + i;
    
    }, 1000);
    <html>
    
    <head>
      <meta charset="UTF-8">
      <title>JavaScript test</title>
    </head>
    
    <body>
      <div id="example">Zahl 1</div>
    </body>
    
    </html>

    Now if you would like to run a PHP Script every second you need something else which is called AJAX. So for example if you would like to run hello.php every one second and set the result of it to the same div from before you need this code:

    var i = 1;
    
    // update site content every second
    setInterval(function() {
    
      // run function loadDoc every second
      loadDoc();
    
    }, 1000);
    
    function loadDoc() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        // get div with id example and update HTML
        document.getElementById("example").innerHTML = this.responseText;
      };
      xhttp.open("GET", "hello.php", true);
      xhttp.send();
    }
    <html>
    
    <head>
      <meta charset="UTF-8">
      <title>JavaScript test</title>
    </head>
    
    <body>
      <div id="example">Zahl 1</div>
    </body>
    
    </html>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄