简体   繁体   English

使用Ajax在Symfony中无限滚动

[英]Infinite scroll in Symfony using Ajax

I wanted to show products from db using infinite scroll. 我想使用无限滚动显示db中的产品。

Here is my Controller: 这是我的控制器:

    $start=0;
    $limit= 6;

    $query = $repository->createQueryBuilder('classified')
        ->join('classified.statusId','status')
        ->andWhere('status.name=:status')
        ->setParameter('status','active')
        ->setFirstResult($start)
        ->setMaxResults($limit)
        ->getQuery();

      $results = $query->getResult();

    if ($request->isXmlHttpRequest()){

        $list = $this->renderView('search-result.html.twig', [
            'results' => $results
        ]);


    $response = new JsonResponse();
    $response->setData(array('classifiedList' => $list));
    return $response;
}

Ajax: 阿贾克斯:

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

        })

        function getmoredata() {
            $.ajax({
                type: "GET",
                url: "{{ path('classified_list', {'type' : 'all'}) }}",
                dataType: "json",
                cache: false,
                success: function (response) {
                        $('.card-deck').append(response.classifiedList);
                        $('#spinner').hide();
                        console.log(response);

                },
                error: function (response) {
                    console.log(response);
                }
            });
        }

So now what is happening is the first 6 results is repeatedly showing when the scrolling is triggered. 所以现在发生的事情是前6个结果重复显示何时触发滚动。 I know this is not correct and I don't expect this to work properly. 我知道这是不对的,我不希望这个工作正常。 But what I don't know is what is the next step. 但我不知道的是下一步是什么。 So do I need to add paginator or something? 那么我需要添加分页器吗?

Any help would be appreciated,Thanks! 任何帮助将不胜感激,谢谢!

You need to track whether your ajax is requesting or not, so it will not do request multiple times when window reach the scroll limit. 您需要跟踪您的ajax是否请求,因此当窗口达到滚动限制时,它不会多次请求。 Also, you need to track the offset and whether you have more data to loads. 此外,您需要跟踪偏移量以及是否有更多数据要加载。 eg 例如

 window.__isFetching = false;
 window.__offset = 0;
 window.__hasMoreData = true;

 $(window).scroll(function () {
    if($(window).scrollTop() + $(window).height()>= $(document).height()){

      if(!window.__isFetching && window.__hasMoreData) {
         getmoredata();
      }
    }

 })

 function getmoredata() {
        window.__isFetching = true;
        $.ajax({
            type: "GET",
            // NOTE, you can pass current offset here in url
            url: "{{ path('classified_list', {'type' : 'all', }) }}"+"&offset="+window.__offset,
            dataType: "json",
            cache: false,
            success: function (response) {
                    $('.card-deck').append(response.classifiedList);
                    $('#spinner').hide();
                    console.log(response);

                   // Note that here, server side response must have next offset and hasMoreData attribut.
                    window.__isFetching = false;
                    window.__hasMoreData = response.hasMoreData;
                    window.__offset = response.offset

            },
            error: function (response) {
                console.log(response);
            }
        });
  }

in server side , which is symfony, you might want to do something like: 在服务器端,这是symfony,你可能想做类似的事情:

// Get offset from request query
$start= $request->query->get('offset');
$limit= 6;

$query = $repository->createQueryBuilder('classified')
    ->join('classified.statusId','status')
    ->andWhere('status.name=:status')
    ->setParameter('status','active')
    ->setFirstResult($start)
    ->setMaxResults($limit)
    ->getQuery();

  $results = $query->getResult();

if ($request->isXmlHttpRequest()){

    $list = $this->renderView('search-result.html.twig', [
        'results' => $results
    ]);


$response = new JsonResponse();
// And add offset and hasMoreData fields in response
$response->setData(array(
  'classifiedList' => $list,
   'offset' => $start += 1
   'hasMoreData' => count($list) < ($limit * &start)
  )
);
return $response;

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

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