繁体   English   中英

当用户仅滚动一次到页面底部时如何使用ajax加载更多内容

[英]How to load more content with ajax when user scrolls to the bottom the of page only once

当用户滚动到页面底部时,我想将html文件附加到div上。 但是我只想这样做一次。 我设法编写了一个可行的脚本,但是在刷新页面几次后,我注意到它随机检索并附加HTML多次。 注意,我正在使用布尔值来控制脚本的一种用途,我预感这可能是我的问题所在。

这是我的脚本和div,后面将附加内容:

**编辑:删除了if(使用== false),因为它是不必要的。 **

 var used = false; $(window).scroll(function () { if ($(window).scrollTop() >= $(document).height() - $(window).height() - 400 && used == false) { $.get("more.html",function(data){ $("#new-content").append(data); used = true; }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="new-content"> </div> 

这是我要附加的HTML

    <div class="double-wrapper">
     <div class="app">
      <div class="app-inner"></div>
     </div>
     <div class="app">
      <div class="app-inner"></div>
     </div>
    </div>
    <div class="inn">
     <div class="inn-inner">
     </div>
    </div>

这是例子。 通过使用第二个布尔作出任何异步调用之前锁定功能,可以保持原有的一个used跟踪该内容已成功添加。 如果请求中有错误(您可以尝试通过无效的URL来更改URL),则used将保持为false,并且该函数可以再次尝试该请求(我添加了一个错误函数来释放锁)。

  var used = false, locked = false; $(window).scroll(function () { //I shortened conditions (for a boolean, "!used" is same as "used == false") if ($(window).scrollTop() >= $(document).height() - $(window).height() - 400 && !used & !locked) { //lock function before the call locked = true; $.get("http://date.jsontest.com",function(data){ //different injection for the test because i used JSON test content //$("#new-content").append(data); $("#new-content").html($("#new-content").html() + '<p>' + JSON.stringify(data) + '</p>'); used = true; //release the lock when results arrive locked = false; }).fail(function(){ console.log('request has failed'); //release the lock on error if you want to be able to try the request again locked = false; }); } }); 
 body{ height: 1000px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="new-content"> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM