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 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler