2014-01-28 100 views
4

我一直工作在一個網站,自動負載上滾動的新內容從MySQL數據庫中。 但問題是,即使滾動可以忽略不計,它也會加載新內容。我的意思是它在滾動時加載新內容,而不是在頁面結束時加載。 可滾動部分位於靜態框架內。AJAX自動加載HTML5的部分

jQuery代碼:

<script type="text/javascript"> 
     $(document).ready(function() { 
     var track_load = 0; //total loaded record group(s) 
     var loading = false; //to prevents multipal ajax loads 
     var total_groups = <?php echo $total_groups; ?>; //total record group(s) 
     $('#results').load("autoload_process.php", {'group_no':track_load}, function() {track_load++;}); //load first group 
     $("#frames").scroll(function() { //detect page scroll 
      if($(window).scrollTop() + $(window).height() == $(document).height()) //user scrolled to bottom of the page? 
      { 
      if(track_load <= total_groups && loading==false) //there's more data to load 
      { 
       loading = true; //prevent further ajax loading 
       $('.animation_image').show(); //show loading image 
       //load data from the server using a HTTP POST request 
       $.post('autoload_process.php',{'group_no': track_load}, function(data){ 
       $("#results").append(data); //append received data into the element 
       //hide loading image 
       $('.animation_image').hide(); //hide loading image once data is received 
       track_load++; //loaded group increment 
       loading = false; 

       }).fail(function(xhr, ajaxOptions, thrownError) { //any errors? 

       alert(thrownError); //alert with HTTP error 
       $('.animation_image').hide(); //hide loading image 
       loading = false; 

       }); 

      } 
      } 
     }); 
     }); 
    </script> 

夥計們,請幫我一下吧。可能有'

$(window).scrollTop()+ $(window).height()== $(document).height()`這個部分存在某種問題。

我要跟蹤的部分不是窗口的滾動。

+0

建議你使用這個插件:http://imakewebthings.com/jquery-waypoints/ – jacquard

回答

3

假設下面標記的一些變化:

<div class="container"> 
    <div class="scroll-content"> 
     <p>Scroll container</p> 
    </div> 
</div> 

CSS

.container { 
    position: relative; 
    height: 400px; 
    width: 300px; 
    overflow-y: scroll; 
} 

.scroll-content { 
    position: relative; 
    height: 1200px; /* height just added for illustrative purposes */ 
    width: 300px; 
    background: #849558; 
} 

這裏的跟蹤你的滾動位置,並在一定範圍內觸發Ajax調用一個方法:

$('.container').scroll(function() { 
    var fromtop = $(this).scrollTop(), 
     height = $(this).find('.scroll-content').innerHeight() - $(this).innerHeight(); 
     // In the above line we're finding the height of the scrollable content 
     // and subtracting the height of the viewable area (or parent container). 

    if ((height - fromtop) < 50) { 
     alert('trigger ajax call'); 
    } 
}); 

< 50代表你的觸發範圍。將其更改爲最適合您的應用程序的任何內容。

的優勢,這種方法是,你在更多的內容已經加載之後,內部容器的高度重新計算。

這裏有一個Fiddle