2009-08-14 71 views
1

我正在鑽研一些AJAX,我試圖利用jQuery。在同一頁面上的多個元素的jQuery AJAX實時更新​​

我有一個索引頁面鏈接到多個頁面,每頁旁邊是一個查看計數。

我希望瀏覽次數刷新並自動更新每隔幾秒鐘,以便頁面上的用戶可以查看頁面計數的實時更新。

我已經討論了以下基於頁面上單個Ajax元素運行良好的腳本,但10或更多?

是否有一種更有效的方法(剪切並粘貼語句10次)以獲得所有字段單獨更新?

<?php 
// File: ajax.php 
    // Ajax refresh hits 
    if(isset($_GET['refresh'])){ 
     // Uses the get_page_views() function which takes an ID and retreives that page view count. The ID is passed by the AJAX script. 
     if($_GET['refresh'] == 'hits') echo get_page_views($_GET['id']); 
    }; 
?> 

這是代碼到HTML頁面。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Ajax - PHP example</title> 

<script language="javascript" type="text/javascript" src="jquery-1.3.2.js"></script> 
<script language="javascript" type="text/javascript"> 
    $(document).ready(function(){ 
     //ajax.php is called every second to get view count from server 
     var ajaxDelay = 1000; 
     setInterval(function(){ 
      // Refresh details. 
      $('#zone-111').load('ajax.php?refresh=hits&id=111'); 
      $(#zone-222').load('ajax.php?refresh=hits&id=222'); 
      $(#zone-333').load('ajax.php?refresh=hits&id=333'); 
      $(#zone-444').load('ajax.php?refresh=hits&id=444'); 
      $(#zone-555').load('ajax.php?refresh=hits&id=555'); 
     }, ajaxDelay); 
    }); 
</script> 

</head> 

<body> 

<div align="center" id="zone-111">--</div> 
<br /> 
<div align="center" id="zone-222">--</div> 
<br /> 
<div align="center" id="zone-333">--</div> 
<br /> 
<div align="center" id="zone-444">--</div> 
<br /> 
<div align="center" id="zone-555">--</div> 
<br /> 

</body> 
</html> 

任何有關如何使這個腳本/代碼更有效的建議將被大大接受。

此致

P.

回答

5

發送所有的ID中的一次作爲JSON陣列。在服務器端,構建一個包含ID /計數的鍵/值對的JSON對象。然後在獲取結果時遍歷客戶端上的鍵並在相關的DIV中依次設置每個計數。

$(document).ready(function(){ 
    //ajax.php is called every second to get view count from server 
    var ajaxDelay = 1000; 
    var ids = []; 
    $('[id^="zone-"]').each(function() { 
     ids.push(this.id); 
    }); 
    setInterval(function(){ 
      $.ajax({ 
       url: 'ajax.php', 
       dataType: 'json', 
       type: 'get', 
       data: { refresh: 'hits', ids: ids }, 
       success: function(data) { 
        for (var key in data) { 
         var div = $('#zone-' + key).html(data[key]); 
        } 
       } 
      }); 
    }, ajaxDelay); 
}); 
0

感謝您的JSON的建議,我不太確定如何雖然實現它,我想出了這個解決方案,到目前爲止,工作得很好。反饋會很好。

<script type="text/javascript" language="javascript"> 
     $(document).ready(function(){ 
      setInterval(function(){ 
       $('.views').each(function(){ 
        $(this).load('ajax.php?id='+this.id); 
       }); 
      }, 5000); 
     });  
    </script> 

而在HTML你剛纔分配類「若干意見」爲您想更新的元素和實體店的「ID」爲ID如:

<p class="views" id="123"><!-- content appears here. --></p> 
相關問題