doubaomao9304 2015-06-07 14:16
浏览 29
已采纳

使用AJAX POST到PHP并在更改时刷新

I am trying to build a web application that needs to refresh the entire page when there is a change in the database. I would like to achieve this using AJAX and PHP. I would like to POST a single piece of information to the PHP script every 5 seconds and if the returned value from the PHP script is different from a predefined variable, I would like to refresh the entire page.

For example, I have a predefined value in javascript of 200. If the PHP script returns a different value, I would like to refresh the entire page.

I know how to write the PHP, it is just the XJAX I am having issues with. I would also not like to use jquery if possible.

Thanks in advance for any guidance!

EDIT : I would not like to use jquery or any other framework, just raw javascript. I also need to refresh the entire page upon change and run the AJAX every 5 seconds.

  • 写回答

3条回答 默认 最新

  • dougou8573 2015-06-07 14:39
    关注

    Good question. You can do if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") { to check if the PHP-side value has changed. This watchdog method is called very 5 seconds through setInterval. If there is a change, then the page is refreshed via document.location.reload(true) (ref) to prevent reusing the cache.

    function watchdog() {
      var xmlhttp;
      if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      } else {
        // code for IE6, IE5 - whatever, it doesn't hurt
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    
      xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    
          // This is how you can discover a server-side change
          if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
            document.location.reload(true); // Don't reuse cache
          }
        }
      };
      xmlhttp.open("POST","page.php",true);
      xmlhttp.send();
    }
    
    // Call watchdog() every 5 seconds
    setInterval(function(){ watchdog(); }, 5000);
    

    Note: I chose setInterval over setTimeout because if the connection to the server fails (500-error, timeout, etc.), then the response logic may otherwise fail to trigger another setTimeout. setInterval ensures the server is polled consistently regardless of connection failures.

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

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line