简体   繁体   English

PHP 和 jquery Ajax 和无限滚动过滤

[英]PHP and jquery Ajax and infinite scroll for filtering

I have applied the infinite-ajax-scroll to my project.我已将无限 ajax 滚动应用到我的项目中。 It is a PHP Laravel project that displays a long list of divs.这是一个 PHP Laravel 项目,显示一长串 div。 Instead of using pagination, I wanted to make the user see all results on the same page by scrolling down.我不想使用分页,而是想让用户通过向下滚动来查看同一页面上的所有结果。 I also have a filter for the results and it works well, but the strange thing is that after the results appear through filtering, scrolling down will lead to the appearance of all results without taking into account the current filter.我也有一个结果过滤器,效果很好,但奇怪的是,结果通过过滤出现后,向下滚动会导致出现所有结果,而不考虑当前过滤器。

Can anyone advise on my best approach to this?任何人都可以就我的最佳方法提出建议吗? I want to use the scrolling and it is something maybe realted to the url but I don't know how to fix this我想使用滚动,它可能与 url 相关,但我不知道如何解决这个问题

Below is what I have so far.以下是我到目前为止所拥有的。

// Filters // 过滤器

    // Search functions
    function storeSearchAjax() {
        var filters = searchFilters();

        $.ajax({
            method: 'get',
            data: filters,
            url: '/restaurants/search-ajax',
            success: function(data) {
                $('#result').html(data);
            }
        });
    }

    function searchFilters() {
        offerFilter = $(".offerCheckbox:checked").map(function () {
            return $(this).val();
        }).get();

        cuisineFilter = $(".cuisineCheckbox:checked").map(function () {
            return $(this).val();
        }).get();

        freedeliveryFilter = $(".freedeliveryCheckbox:checked").map(function () {
            return $(this).val();
        }).get();

        var filters = {
            "offers" : JSON.stringify(offerFilter),
            "cuisines" : JSON.stringify(cuisineFilter),
            "freedelivery" : JSON.stringify(freedeliveryFilter)
        }

        return filters;
    }

    // Paginate links
    $('#result .pagination li a').click(function(e) {
        e.preventDefault();

        var url = $(this).attr('href');
        var params = $.param(searchFilters());

        window.location = url+'&'+params;
    });


    $('input[name="offers[]"], input[name="cuisines[]"], input[name="freedelivery[]"]').change(function(e) {
        e.preventDefault();
        storeSearchAjax();
    });

          var page = 1;

            $(window).scroll(function() {
                if($(window).scrollTop() + $(window).height() >= $(document).height()) {
                    page++;
                    loadMoreData(page);
                }
            });

            function loadMoreData(page) {
                $.ajax({
                    url: '/restaurants/search?page=' + page,
                    type: "get",
                    beforeSend: function() {
                        $('.ajax-load').show();
                    }
                }).done(function(data) {


                    if(data.html=="") {

                        $('.ajax-load').html("");
                        return;
                    }
                    $('.ajax-load').hide();
                    $(".loading_restaurants").append(data.html);

                }).fail(function(jqXHR, ajaxOptions, thrownError) {
                    $('.ajax-load').html("server not responding...");
                
                });
            }

Controller: Controller:

    public function ajaxSearch(Request $request)
   {

       $stores = $this->getStores($request);
  
          Helper::usePaginate();
          $stores = $stores->paginate(15)->setPath('/restaurants/search');
  
          $cuisines = Storecuisine::getStoreCuisines();
          $storedays = Storeday::getStoreDays();
          $storewhours = Storeday::all();
          $isapp_open=Helper::isAppOpen();
  
          return response()->view('store-search.stores_listing', compact('stores','storedays','isapp_open','storewhours','cuisines'));
  }
function loadMoreData(page) {
    var filters = searchFilters();
    $.ajax({
        url: '/restaurants/search?page=' + page,
        data: filters,  // <-- this was missing
        beforeSend: function() {
            $('.ajax-load').show();
        }
    }).done(function(data) {
        if(data.html=="") {
            $('.ajax-load').html("");
            return;
        }
        $('.ajax-load').hide();
        $(".loading_restaurants").append(data.html);
    }).fail(function(jqXHR, ajaxOptions, thrownError) {
        $('.ajax-load').html("server not responding...");
    });
}

UPDATE更新

$(document).ready(function(){
    storeSearchAjax();
});

UPDATE 2更新 2

在此处输入图像描述

single scroll causing 10s of request !单个滚动导致 10s 的请求!

Actually the scroll event is firing too many times even for a "light touch" creating many request for the same filter criteria you need to use some deboucing using library like lodash.实际上,即使对于“轻触”,滚动事件也会触发太多次,为相同的过滤条件创建许多请求,您需要使用lodash 之类的库进行一些去抖动。 So that the event fire less often and won't jam the browser or the server这样事件触发的频率就会降低,并且不会阻塞浏览器或服务器

Add lodash lib.添加 lodash 库。

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>

Remove this code删除此代码

  $(window).scroll(function() {
      if($(window).scrollTop() + $(window).height() >= $(document).height()) {
          page++;
          loadMoreData(page);
      }
  });

Add this instead改为添加

window.addEventListener('scroll', _.throttle(function(){
    if($(window).scrollTop() + $(window).height() >= $(document).height()) {
        page++;
        loadMoreData(page);
    }
}, 500));

UPDATE 3更新 3

For the second issue, don't increment page on scroll rather do on the ajax success callback.对于第二个问题,不要在滚动时增加页面,而是在 ajax 成功回调上进行。 And also one more thing: currently its doing ajax even if we scroll up which is wrong instead it should do ajax only when we scroll down MORE than the previous deepest point for that you need to store the deepest scroll value in some variable and use that to compare whether use has scrolled MORE deep than the previously done还有一件事:目前它正在做 ajax 即使我们向上滚动这是错误的,而是它应该做 ajax 只有当我们向下滚动比之前的最深点更多时,您需要将最深的滚动值存储在某个变量中并使用它比较 use 是否比以前滚动得更深

//create on global var say 
var deepestPoint = 0;

window.addEventListener('scroll', _.throttle(function(){
    if( 
       ( $(window).scrollTop() + $(window).height() >= $(document).height() )
       &&  ($(window).scrollTop() > deepestPoint )
    ) {
        page++; //<--Remove this from here
        loadMoreData(page);
        deepestPoint = $(window).scrollTop();
    }
}, 500));

//And then


 }).done(function(data) {
        if(data.html=="") {
           $('.ajax-load').html("");
           return;
        }

        $('.ajax-load').hide();
        $(".loading_restaurants").append(data.html);
        //<--paste here
 }).fail(function(jqXHR, ajaxOptions, thrownError) {
                $('.ajax-load').html("server not responding...");
 });

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

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