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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应