简体   繁体   中英

How to make one ajax request instead of multiple on endless scroll implementation

I load every next 10 publication to the feed, when user scrolls to the bottom. The problem is ajax sends multiple requests since this code detects multiple scroll-to-bottom events. How to make one ajax request instead of multiple, considering that user scroll further down?

$(window).scroll(function() {

    if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {           

        $.ajax({
            url: '/more/',
            type:'GET',
            dataType: 'json',
            data:2,
            success: function (data) {
                alert(data);          
            }
        });
    }
});

try this

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       alert("bottom!");
   }
});

Use a lock to check if ajax is still in operation and don't make next ajax call till you receive data through ajax, after which you can free the lock.

var lock = false;

$(window).scroll(function() {

if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {           

if(lock==true){
return;

}

lock = true;        

$.ajax({
            url: '/more/',
            type:'GET',
            dataType: 'json',
            data:2,
            success: function (data) {
                alert(data);                              
            }
        }).always(function() {
            lock = false;
        });
    }
});

Try this:

 $(window).scroll(function() { if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) { var jqXHR = $(document).data("jqXHR"); if(jqXHR) { return; } jqXHR = $.ajax({ url: '/more/', type: 'GET', dataType: 'json', data: 2, success: function(data) { alert(data); } }); $(document).data("jqXHR", jqXHR); jqXHR.always(function(){ $(document).removeData("jqXHR"); }); } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM