首页 > 解决方案 > 在滚动功能中显示 Ajax 调用之前的加载

问题描述

我需要用分页加载通知

如果用户滚动到特定高度,我需要加载下一组通知....

这是我的html

                            <div id="data" >
                            </div>

这是我的 Ajax 调用

$('.notify').scroll(function() {
    var scrollTop = $(this).scrollTop() ;//how much has been scrolled
    var innerHeight = $(this).innerHeight() ;//inner height of the element
    var scrollHeight = 950;
    if(scrollTop + innerHeight >= (scrollHeight -50)) {
    $.ajax({
        url: url,
        type: 'GET',
        success: function(data){
        $('.notification-body').scrollTop($('.notification-body')[0].scrollHeight);
        $('#data').append(response).show().fadeIn("slow");
        },
    });
    }

我想在 Ajax 调用之前附加一个 Loading .... 并在它完成后将其删除.....

我试过这个

$('.notify').scroll(function() {
    var scrollTop = $(this).scrollTop() ;//how much has been scrolled
    var innerHeight = $(this).innerHeight() ;//inner height of the element
    var scrollHeight = 950;
    if(scrollTop + innerHeight >= (scrollHeight -50)) {
    $.ajax({
        url: url,
        type: 'GET',
        beforeSend:function(){
                $('#data').append('Loading........').show().fadeIn("slow");
            },
        success: function(data){
        $('.notification-body').scrollTop($('.notification-body')[0].scrollHeight);
        $('#data').append(response).show().fadeIn("slow");
        },
    });
    }

怎么做但是它来了很多次

标签: javascriptjquery

解决方案


如果问题是在一次滚动中多次调用 ajax 调用,则可以添加某种加载布尔值。这样,在第一次调用完成之前,它不会再次被调用。或者,您还可以使用 setTimeout 使加载最小长度,这样加载和不加载之间的切换就不会太突然。

$('.notify').scroll(function() {
var scrollTop = $(this).scrollTop() ;//how much has been scrolled
var innerHeight = $(this).innerHeight() ;//inner height of the element
var scrollHeight = 950;
if(scrollTop + innerHeight >= (scrollHeight -50) && !this.loading) {
  this.loading = true
  $.ajax({
    url: url,
    type: 'GET',
    beforeSend:function(){
            $('#data').append('Loading........').show().fadeIn("slow");
        },
    success: function(data){
    $('.notification-body').scrollTop($('.notification-body')[0].scrollHeight);
    $('#data').append(response).show().fadeIn("slow");
    setTimeout(()=>{this.loading = false}, 500)
    },
});
}

推荐阅读