2014-01-28 37 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