簡體   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