2011-06-02 110 views
0

我有一個PHP頁面,需要刷新每5秒。在嵌入ajax文件時,我沒有發現在Firebug中發生的更新。這裏是代碼的骨架:刷新PHP頁面使用ajax

**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); 
} 

回答

9

雖然它可能不是理想的解決方案,jQuery提供的正是這種實現的一個非常簡單的方法:

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

我不知道,將工作完美的,一段時間沒有完成,但它是我相信的更優雅的解決方案。

2

爲什麼不只是將<meta http-equiv="refresh" content="5">標籤放入您的<head>?它會每隔5秒刷新頁面而不需要任何javascript。

+0

因爲我需要更新以及每5secs數據庫。 – 2011-06-02 19:59:50

+0

在您的PHP代碼中觸發它們,因爲每次頁面刷新時都會運行它 – Ryan 2011-06-02 20:00:32

+0

似乎沒有工作。這真的很奇怪!是否因爲notification.php在開始時創建了一個cookie? – 2011-06-02 20:12:13

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> 

這個代碼definetly幫助你。 或我們可以使用 -

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