使用ajax刷新PHP页面

nam*_*ked 0 php ajax

我有一个需要每5秒刷新一次的php页面.在嵌入ajax文件时,我发现Firebug中没有更新.这是代码的骨架:

**notification.php**
<?php
       ....
       ....
?>
<html>
     <head>
     <script src="./refresh.js"></script>
     <script type="text/javascript">
         refreshContents();
     </script>
     </head>
     <body>
            ....

            <div id="identifier">
               <p>Waiting area</p>
            </div>
      </body>
</html>


**refresh.js**

var seconds = 5;
var content = "identifier";
var url = "notification.php";

function refreshContents()
{
   var xmlHttp;
   try
   {
      xmlHttp = new XMLHttpRequest();
   }
   catch(e)
   {
      try
      {
         xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch(f)
      {
         try
         {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch(g)
         {
            alert("Browser not supports Ajax");
            return false;
         }
      }
   }


   xmlHttp.onreadystatechange=function()
   {
      if (xmlHttp.readyState == 4)
      {
         document.getElementById(content).innerHTML = xmlHttp.responseText;
         setTimeout('refreshContents()', seconds*1000);
      }
   }

   xmlHttp.open("GET", url, true);
   xmlHttp.send(null);
}

var seconds = 5;
window.onload = function startrefresh(){
   setTimeout('refreshContents()', seconds*1000);
}
Run Code Online (Sandbox Code Playgroud)

jrb*_*ano 9

虽然它可能不是理想的解决方案,但jQuery有一个非常简单的方法来实现这个:

$(document).ready(function () {
  function reload() {
    $("#content").load("notification.php");
  }
  setTimeOut(reload, seconds*1000)
}
Run Code Online (Sandbox Code Playgroud)

我不确定它是否会完美运行,但有一段时间没有完成,但它确实是一个更优雅的解决方案.