如何只进行一次 Ajax 调用



我有以下代码,当用户滚动到屏幕底部时触发。唯一的问题是,我只想让阿贾克斯调用一次。我的代码是:

        var w = $(window);
        window.onscroll = function(ev) {
            if ($(document).height() - w.height() == w.scrollTop()) {

              $('#loading-image').show();
              $.ajax({
                    url: "page-2.html",
                    cache: false,
                    success: function(result){
                      $("#part2").html(result);
                      console.log();
                    },
                    complete: function(){
                      $('#loading-image').hide();
                    }
              });

            }
        };

最简单的方法可以添加全局变量并通过以下方式检查它:

var w = $(window);
var BOTTOM_REACHED = false;
window.onscroll = function(ev) {
  if ($(document).height() - w.height() == w.scrollTop() && !BOTTOM_REACHED) {
      BOTTOM_REACHED = true;
      $('#loading-image').show();
          $.ajax({
                url: "page-2.html",
                cache: false,
                success: function(result){
                  $("#part2").html(result);
                  console.log();
                },
                complete: function(){
                  $('#loading-image').hide();
                  BOTTOM_REACHED = false;
                }
          });

        }
    };
你可以

这样尝试:

var bottom_reached = false;
        $(window).scroll(function(){
        if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
            bottom_reached = true;
              $('#loading-image').show();
             if(bottom_reached)
             {
               bottom_reached = false;
              $.ajax({
                    url: "page-2.html",
                    cache: false,
                    success: function(result){
                      $("#part2").html(result);
                      console.log();
                    },
                    complete: function(){
                      $('#loading-image').hide();
                    }
              });
             }
            }
          });

最新更新