【问题标题】:How do you make an Ajax call when a user scrolls down to the bottom of the screen当用户向下滚动到屏幕底部时如何进行 Ajax 调用
【发布时间】:2017-06-18 14:54:13
【问题描述】:

我想在用户向下滚动到屏幕底部时进行 Ajax 调用。出于某种原因,我的代码无法正常工作。我认为这可能是语法错误,但我检查了控制台并没有看到错误。欢迎任何建议、改进或示例。

<div id="content">
<?php include('post-1.php'); ?>
</div>

<div id="loading-image" style="display: none;"></div>
<div id="part2"></div>
<script>
window.onscroll = function(ev) {
  if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {

  $('#loading-image').show();
  $.ajax({
        url: "<?php echo get_stylesheet_directory_uri();?>/post-2.php",
        cache: false,
        success: function(html){
          $("#part2").html(result);
        },
        complete: function(){
          $('#loading-image').hide();
        }
  });


}
};
</script>

【问题讨论】:

  • 您“认为这可能是语法错误”? Open the browser's console 看看有没有错误,不用猜测了。
  • 使用this 条件。它可能会起作用
  • @Nimish 当然我已经查看了控制台但我没有看到错误
  • @mplungjan 我已经这样做了。这就是我在这里的原因。寻找一个清晰简洁的答案
  • 如果控制台中没有错误信息,则说明没有语法错误。

标签: javascript php jquery ajax


【解决方案1】:

你可以使用 this.Works here

function CallAjax(){
      $.ajax({
        url: "<?php echo get_stylesheet_directory_uri();?>/post-2.php",
        cache: false,
        success: function(html){
          $("#part2").html(result);
        },
        complete: function(){
          $('#loading-image').hide();
        }
      });    
}

$(window).scroll(function() {
       var divTop = $('#yourDivId').offset().top,
           divHeight = $('#yourDivId').outerHeight(),
           wHeight = $(window).height(),
           windowScrTp = $(this).scrollTop();
       if (windowScrTp > (divTop+divHeight-wHeight)){
            console.log('reached');
            // add your ajax method here;
            CallAjax();
       }
});

【讨论】:

    猜你喜欢
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2012-02-25
    • 1970-01-01
    • 2018-12-06
    • 2013-12-25
    • 2019-05-31
    相关资源
    最近更新 更多