2009-11-13 112 views
0

我是新來的。我只是創建一個可以從MySQL數據庫讀取數據的代碼。 但是,當我添加數據庫內的新數據,我的PHP頁面不能更新自己的自動。 我希望頁面可以自動更新,我可以按下f5按鈕並刷新。 任何人都可以幫我解決這個問題嗎?如何自動更新數據庫而不用ajax刷新?

得到任何misstake?

<script type="text/javascript"> 
function List(){ 
    var ajaxRequest; 
    var selectedProduct = ""; 
    var product = document.getElementById('product'); 
    var output ="";   
    var k = 0; 
// var name = new Array; 
// var model = new Array; 
    var unitprice = new Array; 
    var queryString = new Array; 

    queryString = "&name=" + txtname + "&model=" + txtmodel + ; 
      ajaxRequest.open("GET", $productPrice + queryString, true); 
      ajaxRequest.send(null); 
    ajaxRequest.open("GET", $productPrice + queryString, true); 
    ajaxRequest.send(null); 

     <?php foreach ($productPrices as $price): ?> 
      name[k] = "<?php echo $price['Product']['txtname']; ?>"; 
      model[k] = "<?php echo $price['Product']['txtmodel']; ?>"; 
      k++; 

     <?php endforeach; ?> 

     k=0; 
     for (var i = 0; i < product.length; i++) { 
       k = product.options[i].value; 

      if (product.options[i].selected) { 
       output += '<tr>'+ 
           '<td style="border-right: 0px; width:270px; text-align:center" id="ProductProduct'+k+'" name="data[Product][Product]['+k+']">'+name[i]+'</td>'+ 
           '<td style="border-right: 0px; width:100px; text-align:left" id="ProductProduct'+k+'" name="data[Product][Product]['+k+']">'+model[i]+'</td>'+ 
          '</tr>';  
      } 
     } 
     output = '<table style="width:500px; border: 0px;">'+output+'</table>';   
     document.getElementById('productTable').innerHTML = output; 
}     
</script> 
+1

javascriptlibrary可能會使這項工作更容易 – Natrium 2009-11-13 07:47:14

+0

是的,儘管你在哪裏調用Function List? – LiamB 2009-11-13 07:51:25

+0

與使用jQuery? – 2009-11-13 07:56:20

回答

1

您需要在頁面中進行某種重複的AJAX檢查,以查看數據庫中是否有新數據。你可以使用setTimeout或setInterval來做到這一點。

E.g.

function CheckData() { 
    List(); 
    setTimeout(CheckData, 10000); 
} 
+0

@ck:只是一個評論,我不知道我們在談論多少數據,有多少用戶,但是這將加載服務器*快* ... – RageZ 2009-11-13 08:04:31

+0

@RageZ - 它只是一個潛在的解決方案。超時時間可以延長,理想情況下應該進行分析以使最慢的部分更有效。 – cjk 2009-11-13 08:45:47

0
setInterval(function() { 
    List(); // your function 
     // Do something every 2 seconds 
}, 2000); 

這是jQuery的功能,這將幫助你。