jQuery ajax无限滚动重复ajax调用

时间:2016-03-16 13:20:14

标签: jquery ajax duplicates

我正在调用ajax调用但是当我滚动2次调用重复的ajax调用时..对于两个卷轴我得到重复ajax call.can任何人都帮我如何纠正重复的ajax调用。

jQuery(function($){       
    $('#infscr-loading').hide();
    $(window).scroll(function() { //detect page scroll
        if($(window).scrollTop() == $(document).height() - $(window).height()) {
            var key = $(".tab-content div.active").attr("id"); 
            var offset = $(".tab-content div.active .movie_boot .movie-beta__item").length;
            var data1 = $("#yr").val();             
            url = "/loop-movies/?offset="+offset+'&key='+key+'&yr='+data1;
            $.ajax({
                type       : "post",
                url        : url,
                delay      : 500, 
                beforeSend : function(){
                    $('#infscr-loading').show();
                },
                success    : function(response) {   
                    $(".tab-content div.active .movie_boot").append(response);
                    $('#infscr-loading').hide();
                }
            });         
        }
    });
});

2 个答案:

答案 0 :(得分:1)

var flag;
if (flag.readyState == 4 && flag.status == 200) {
  flag = $.ajax({
    type: "post",
    url: url,
    delay: 500,
    beforeSend: function() {
      $('#infscr-loading').show();
    },
    success: function(response) {
      $(".tab-content div.active .movie_boot").append(response);
      $('#infscr-loading').hide();
    }
  });
}
else{
   alert("AJAX is going on")
}

Demo Fiddle显示工作

<强> Reference

答案 1 :(得分:0)

为了实现该行为,您无需依赖 onScroll 事件,只需使用 Vanilla JavascriptIntersectionObserver API

您需要做的就是放置元素并监听它们何时在屏幕中可用,并拥有一个全局变量(在您的场景中),当它到达时切换到 hasMoreItems = truehasMoreItems = false结束或正在加载

您可以使用几行 javascript 和 html 行来实现这一点,而且 much more performant 比在浏览器中侦听滚动事件要//Instantiating the File class String filePath = "C:\\\\Users\\\\taylo\\\\Astronomy\\\\Which Bright Stars Are Visible\\\\StoreVerificationCodes.txt"; //Instantiating the Scanner class to read the file Scanner sc = new Scanner(new File(filePath)); //instantiating the StringBuffer class StringBuffer buffer = new StringBuffer(); //Reading lines of the file and appending them to StringBuffer while (sc.hasNextLine()) { buffer.append(sc.nextLine()+System.lineSeparator()); } String fileContents = buffer.toString(); System.out.println("Contents of the file: "+fileContents); //closing the Scanner object sc.close(); String oldLine = "Code: 12345"; String newLine = ""; //Replacing the old line with new line fileContents = fileContents.replaceAll(oldLine, newLine); //instantiating the FileWriter class FileWriter writer = new FileWriter(filePath); System.out.println(""); System.out.println("new data: "+fileContents); writer.append(fileContents); writer.flush(); writer.close();

我最近整理了一篇关于无限滚动和这种特定行为的文章here