简体   繁体   中英

Gathering proper onScroll data to trigger AJAX function

I am calling an AJAX function on scroll with this:

// Collecting scroll info
$('.overthrow').each(function() {

  var self = this;
  var path2root = ".";
  var subcategoryId = $(this).attr('data-subcategoryId');
  var page = 1;

  $(this).bind('scroll', function() { 

    var scrollAmount = $(self).scrollLeft();
    var documentWidth = $(self).data('currentElementPosition') || $(document).width();
    var scrollPercent = (scrollAmount / documentWidth) * 100;

    if (scrollPercent > 80) { 

      page++;

      console.log("process.php?subcategoryId=" + subcategoryId + "&page=" + page);

      // AJAX function for processing JSON
      $.ajax({
        url: "process.php?subcategoryId=" + subcategoryId + "&page=" + page,
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
          for(i = 0 ; i < data.length; i++) {
            var articleId = data[i].articleResult.articleId;
            var title = data[i].articleResult.title;
            var subhead = data[i].articleResult.subhead;
            var image = data[i].articleResult.image;
            var response = "<td><div class='articleResult'><a href='" + path2root + "/article/article.php?articleId=" + articleId + "'><img src='" + image + "' width='120'/></a><br><h3><a href='" + path2root + "/article/article.php?articleId=" + articleId + "'>" + title.substring(0,25) + "</a></h3></div></td>";

            var appendedData = $(self).find("table tbody tr td:last-child").after(response).fadeIn('slow');
            $(self).data('currentElementPosition', appendedData.position().left);
          };
        }
      });
    };
  });
});

My problem is once the first response is appended to the content and I begin to scroll past 80% into the new results, each pixel I scroll calls the same AJAX function again & again, rather than waiting for the user to scroll the 80% width of the new window size. Effectively making an AJAX call for each pixel scrolled past 80%.

Is an if statement the wrong route to go with something like this? Should I be providing some type of callback to dynamically drive the integers that trigger the AJAX function?

我会使用jQuery的one()来绑定它一次,然后在成功回调中为你的ajax重新绑定它(或之后的任何地方)

Another approach is to save a reference to whatever you append to the DOM as a result of your AJAX call, get its position, and compare your scroll position to that. In other words, assuming that in your example above, $(this) is the parent container in which all data returned via AJAX is inserted into, you could do something like this:

$(this).scroll(function () {
               var scrollAmount = $(this).scrollLeft();
               var documentWidth = $(this).data('currentElementPosition') || $(document).width()
               var scrollPercent = (scrollAmount / documentWidth ) * 100;
                  if (scrollPercent > 80) { 
                      // AJAX function success
                          var appendedData = $(data_returned_from_ajax_call).appendTo($(this))
                          $(this).data('currentElementPosition', appendedData.position().left)
                     };
                  });
}

Just an FYI, an important thing to note is that jQuery's .offset() method will give you the position of the element relative to the document, while .position() will give you the position relative to its parent container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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