簡體   English   中英

滾動條到達底部后如何執行Ajax調用

[英]How to Execute ajax call after the scroller reaches the bottom

我正在糾正對200個對象的數組進行延遲加載的工作,並且提供了API以從服務器提取JSON (通過將索引,行數作為參數獲取get AJAX並在響應時獲取了數據和是否為Boolean的布爾值是否有更多行)。 但是問題是,最初我可以從200中獲得10的數據,但是當我在div上設置滾動功能時,它會顯示重復的數據,這些數據已經附加在div 在這個問題上呆了一天。

希望你們對我有所啟發。

var listgen = (function() {

  var mc = {};
  mc.startindex = 1;
  mc.rowcount = 10;
  mc.hasmorerows = false;
  mc.entity = "requests"

  //Declared variables:

  mc.initComponent = function() {
    var entity = "requests";
    mc.callAjaxForList(mc.entity, mc.startindex, mc.rowcount);
    $("#reqbody").on('scroll', function() {
      if (mc.hasmorerows && ($(this)[0].scrollHeight <= $(this).scrollTop() + $(this).innerHeight())) {
        console.log('reached')
        mc.callAjaxForList(mc.entity, mc.startindex, mc.rowcount);
      }
      console.log("scroll");
    })

  }
  mc.callAjaxForList = function(entity, startindex, rowcount) {
    var options = {
      "list_info": {
        "row_count": rowcount,
        "start_index": startindex
      }
    }
    $("#reqbody").addClass("loading");
    $.ajax({
      url: "/data/" + entity,
      data: {
        "input_data": JSON.stringify(options)
      },
      contentType: "application/json; charset=utf8",
      type: "GET",
      success: function(json) {
        mc.hasmorerows = json.list_info.has_more_rows
        mc.onDataLoading(json);

      },
    });
  }

  mc.onDataLoading = function(json) {
    //this is where i  append the data from the json
    mc.startindex += mc.rowcount
  }

  return mc;
})()

listgen.initComponent();

Scroll是一個非常頻繁的事件,因此我認為在實際調用onDataLoading之前,您已經有多個具有相同數據的Ajax調用,並且范圍增加了。 因此,我應該添加互斥鎖。

  // ... 
  mc.loaging = false; // mutex

  $("#reqbody").on('scroll', function(){
      if(mc.hasmorerows && ($(this)[0].scrollHeight<=$(this).scrollTop()+$(this).innerHeight())){
          console.log('reached')
          if (!mc.loading) // add check here
             mc.callAjaxForList(mc.entity,mc.startindex,mc.rowcount);
      }
       console.log("scroll");
      })
  }
   mc.callAjaxForList= function(entity,startindex,rowcount){ 
    // ...
    mc.loading = true;
     $.ajax({
       // ... 
       success:function(json){
            mc.hasmorerows=json.list_info.has_more_rows
            mc.onDataLoading(json)  ;  
            mc.loading = false;
        },
        error: ()=> mc.loading = false
      });
    }

因此,我們的mc.loading會告訴我們ajax是否已經完成(不要忘記在ajax錯誤時重置其值)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM