2014-01-24 167 views
0

我正在嘗試每三秒鐘讀取數據而不重新加載頁面。我在我的腳本中丟失了一些東西,因爲它在我重新加載頁面之前不會刷新數據。提前致謝。的使用javascript每3秒刷新一次PHP數據

<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title>Testing</title>  
     <!-- below script is for jquery --> 
     <script type="text/javascript" src="js/jquery-1.4.2.js"></script> 
     <script type="text/javascript"> 
      function refreshData(){ 
       $.ajax({ 
       url: 'localhost/index1.php', 
       type:"POST", 
       data:"dataPost", 
       success: function(data){ 
       document.getElementById("dataPost").innerHTML = data; 

        //render the dynamic data into html 
       } 
       }); 
      } 
      setInterval(refreshData, 3000); 
      </script> 
    </head> 
    <div id="dataPost"> 
    <?php 
     $conn = mysql_connect('localhost','user','password');  
     $db = mysql_select_db('db',$conn); 
     $query = "select * from table"; 
     $result = mysql_query($query); 
     while($row = mysql_fetch_array($result)) 
     { 
      echo $row['data1']."<br/>"; 
     } 
    ?> 
    </div>  
</html> 
+4

檢查控制檯是否有錯誤? – j08691

+0

我試過它不起作用。控制檯不顯示任何錯誤,它只是不按特定間隔刷新數據 – rutulPatel

+0

開發工具的網絡選項卡顯示什麼? – j08691

回答

0

我發現它那樣做的原因是javascript的版本。我用1.8.0,它開始工作正常。它一直在工作,但谷歌瀏覽器版本問題。我做了很少的研究,並嘗試更改版本號,它工作。

+0

版本的jQuery請,而不是JavaScript – Kaz

0

,而不是調用頁面本身,把PHP代碼了DIV到一個單一的PHP文件並調用AJAX調用中的這個文件。就這樣。

2

我同意@Axel,但由於Ajax是一個異步函數,即使您的PHP代碼位於外部文件中,您仍然會遇到計時問題。

基本上,您無法知道完成Ajax調用需要多長時間(想象服務器正忙或關閉),因此手動設置間隔爲每3秒毫無意義。您需要將其設置爲距上次完成3秒。

在你的PHP - 只需把你的腳本放在一個外部文件(即script.php)。

在你的Javascript -

  1. 。移動的setInterval()的成功事件中,並使用 的setTimeout()代替。
  2. 創建document.ready事件並從中調用refreshData()。

    <script type="text/javascript"> 
        $(document).ready(function() { 
        refreshData(); 
        }); 
           function refreshData(){ 
            $.ajax({ 
            url: 'localhost/script.php', 
            type:"POST", 
            data:"dataPost", 
            success: function(data){ 
            document.getElementById("dataPost").innerHTML = data;//why not use $('#dataPost').html(data) if you're already using jQuery? 
             setTimeout(refreshData, 3000);//will make the next call 3 seconds after the last one has finished. 
             //render the dynamic data into html 
            } 
            }); 
           } 
    
           </script> 
    

而且你的PHP文件(的script.php)看起來像:

<? 
     $conn = mysql_connect('localhost','user','password');  
     $db = mysql_select_db('db',$conn); 
     $query = "select * from table"; 
     $result = mysql_query($query); 
     while($row = mysql_fetch_array($result)) 
     { 
      echo $row['data1']."<br/>"; 
     } 
    ?> 

希望這有助於。

P.S很多人會指出,mysql_connect已被棄用,所以最好開始使用MySQLi或PDO。

+0

它沒有工作,直到我改變了JavaScript的版本號。但我同意你的看法,顯示的方式是正確的。 +1。謝謝。 – rutulPatel

+0

很高興我能幫到你。你標記了正確的答案嗎? – Yani

+0

正確的答案是改變JavaScript的版本。谷歌瀏覽器不拾起舊的JavaScript,所以我改爲1.8.0版本,它工作正常。 – rutulPatel