【问题标题】:javascript wait until data is loadedjavascript 等到数据加载完毕
【发布时间】:2020-11-22 13:03:08
【问题描述】:

我有以下功能

<script src='jquery-3.1.1.min.js'></script>
<script type='text/javascript'>

$(document).ready(function() {

    function loaddata() {

    var div = $('#div');
        $.get('load_data.php', function(data) { 
            div.html(data);
            $('body, html').scrollTop(div[0].scrollHeight);
        });
    }
    loaddata();
    setInterval(loaddata, 1000);
});


window.addEventListener('scroll', function(){
    if(($(window).scrollTop() < 1) )
    {
        $.ajax({url: 'load_extra_data.php,
                cache: false,
                success: function(html){ $('#div').prepend(html);
                    $(document).scrollTop(position);
        }})
    }
})

</script>

问题与功能有关

window.addEventListener('scroll', function(){

函数 load_extra_data.php 提供了必须添加到 div 的数据。 我需要等到从 load_extra_data.php 获取数据后才能再次滚动。

如何解决问题?

【问题讨论】:

    标签: javascript scroll infinite-scroll


    【解决方案1】:

    保留一个标志来告诉您是否有数据加载,并且在设置标志时不要要求更多数据。大致:

    var loading = false;                             // The flag, initially false
    window.addEventListener('scroll', function(){
        if (!loading && $(window).scrollTop() < 1) {
    //      ^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Checking the flag
            loading = true;                          // Setting the flag
            $.ajax({
                url: 'load_extra_data.php',
                cache: false,
                success: function(html){
                    $('#div').prepend(html);
                    $(document).scrollTop(position);
                },
                complete: function() {               // Clearing the flag when
                    loading = false;                 // the request ends (whether
                }                                    // it succeeds or fails)
            });
        }
    });
    

    (我只使用了 ES5 和更早的特性,因为你的代码没有显示出包含 ES2015+ 项目的迹象。但是在 2020 年,我肯定会写信到 ES2015+ 并转译,如果我真的必须支持不支持它的过时环境。)

    【讨论】:

    • 如果 load_extra_data.php 提供的数据不包含图片,则此解决方案有效。如果存在图片,则滚动条的位置是错误的。有什么想法吗?
    • 上述问题与您正在加载的内容无关。如果您有与特定内容相关的新问题,请使用minimal reproducible example 发布一个新问题以展示该问题。
    【解决方案2】:

    您可以使用 $.ajax() 的回调函数 .done()。数据加载完成后执行。

    $.ajax({url: 'load_extra_data.php',
        cache: false,
        success: function(html){ $('#div').prepend(html);
        $(document).scrollTop(position);
    }}).done(function() {
      // Executed after $.ajax fetch is done
    })
    

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 2021-12-18
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多