使用ajax刷新PHP页面

时间:2011-06-02 19:35:25

标签: 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);
}

3 个答案:

答案 0 :(得分:9)

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

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

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

答案 1 :(得分:3)

为什么不将<meta http-equiv="refresh" content="5">标记放入<head>?它将每5秒刷新一次页面,无需任何javascript。

答案 2 :(得分:1)

请参阅以下示例:

<html>
<head>
<title>Refresh a page in jQuery</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<button id="PageRefresh">Refresh a Page in jQuery</button>
<script type="text/javascript">
$('#PageRefresh').click(function() {
          location.reload();
});
</script>
</body>
</html>

这段代码绝对可以帮到你。 或者我们可以使用 -

 <meta http-equiv="refresh" content="5">