jquery/ajax无限滚动事件

jquery/ajax infinite scroll event

本文关键字:滚动 事件 无限 ajax jquery      更新时间:2023-09-26

我正在尝试在我的web应用程序上使用ajax、php、mysql进行自己的无限滚动。然而,我找不到每次用户是页面末尾时加载新内容的方法。

目前,只要用户点击页面末尾,它就会加载所有数据。

有没有办法让我的脚本"等到最后一页加载完毕"。

$( ".places-wrapper ").scroll(function(){
var windowHeight = $( ".places-wrapper" ).height();
var documentHeight = $( ".places-wrapper")[0].scrollHeight;
var scrollFromTop = $( ".places-wrapper" ).scrollTop();
var margin = 70;
if( scrollFromTop >= documentHeight - windowHeight - margin){
loadNextPage();
}
function loadNextPage(){
    var PlaceID = $( "input[name='placeID']:last" ).val();
    var lastHitDate = $( "input[name='hitDate']:last" ).val();
    $.ajax({
        # .append the new stuff
           });
}
});

我想您需要的是一个标志来告诉脚本页面正在加载。你可以尝试这种方法:

// add a variable as flag
var isLoading = false;
if( scrollFromTop >= documentHeight - windowHeight - margin){
     if ( !isLoading )
     {
        isLoading = true;
        loadNextPage();
     }    
}

// inside your ajax's success callback:
.success(function(){
    isLoading = false;
    // add the page contents
})

正如您猜测的那样,您需要一个外部变量来打开和关闭"加载更多位置"。

var scrollActiveTimer = false;
$(".places-wrapper").scroll(function(){
    // Don't continue if a previous ajax request is still active
    if(scrollActiveTimer == true){
        return;
    }
    // For an improved performance you should try to minimize the jquery DOM searches    
    var wrapper = $(".places-wrapper");
    var windowHeight = wrapper.height();
    var documentHeight = wrapper[0].scrollHeight;
    var scrollFromTop = wrapper.scrollTop();
    var margin = 70;
    var scrollEndPosition = documentHeight - windowHeight - margin;
    if( scrollFromTop >= scrollEndPosition){
        loadNextPage();
    }
    function loadNextPage(){
        // Disable the loading of further pages for the moment
        scrollActiveTimer = true;
        var PlaceID = $("input[name='placeID']:last").first().val();
        var lastHitDate = $( "input[name='hitDate']:last" ).val();
        // Activate the loading event again
        scrollActiveTimer = false;
         $.ajax({
             // parameters..
         }).success(function(data){
             // copy data into html
             wrapper.append(data);
             // Activate the loading event again
             scrollActiveTimer = false;
         });
    }
});

我摆弄了一些伪函数来模拟ajax请求和html生成:http://jsfiddle.net/Macavity/f77xmho7/2/