Home > PHP Framework > ThinkPHP > How to achieve infinite scrolling using ThinkPHP6

How to achieve infinite scrolling using ThinkPHP6

王林
Release: 2023-06-21 08:46:43
Original
1177 people have browsed it

With the continuous development of the Internet, infinite scrolling has become an important element of modern web design. The infinite scroll effect can help improve user experience, allow users to obtain information more easily, and increase user stickiness. This article will introduce how to use the ThinkPHP6 framework to achieve infinite scrolling effect.

  1. Introducing the jQuery framework

Before implementing infinite scrolling, you first need to introduce the jQuery framework. You can use a CDN to speed up access, or download jQuery locally to obtain more stable access.

  1. Build a basic HTML template

In HTML, you need to define the template of the list according to the following structure:

<div id="infinite-scroll">
    <ul id="list">
        <li>第一条数据</li>
        <li>第二条数据</li>
        <li>第三条数据</li>
        ...
    </ul>
    <div id="loading">Loading...</div>
</div>
Copy after login

Among them, # infinite-scroll is a large container used to wrap the entire list. #list is a container used to display data. #loading is a container used to display loading prompts.

  1. Write Ajax request code

Before implementing infinite scrolling, you need to write Ajax request code. You can use jQuery's $.ajax() method to achieve this:

$.ajax({
    url: "/path/to/server", // 请求的服务器地址
    type: "POST", // 请求方式
    data: {'last_id' : last_id}, // 最后一个数据的id
    dataType: "json", // 数据类型
    beforeSend: function () {
        $("#loading").show(); // 显示加载提示
    },
    success: function (data) {
        if(data.status == 200){
            // 成功获取数据
            var html = "";
            $(data.data).each(function (index, item) {
                html += '<li>' + item.title + '</li>';
            });
            $("#list").append(html); // 将获取的数据追加到列表中
            last_id = data.last_id; // 更新最后一条数据的id
        } else {
            // 数据获取失败
            alert(data.message);
        }
    },
    complete: function () {
        $("#loading").hide(); // 隐藏加载提示
    },
    error: function () {
        alert("数据获取失败,请稍后重试");
    }
});
Copy after login

After the request is successful, data in JSON format will be returned. You can get the returned data through $(data.data), and then append it to the data container.

  1. Achieve infinite scrolling effect

When the user scrolls to the bottom of the list, an Ajax request for data will be triggered. You can achieve the infinite scrolling effect through the $(window).scroll() method:

$(window).scroll(function () {
    if ($(document).scrollTop() + $(window).height() > $(document).height() - 100) {
        // 检测用户滚动到底部
        loadMore();
    }
});

function loadMore() {
    $.ajax({
        url: "/path/to/server",
        type: "POST",
        data: {'last_id' : last_id},
        dataType: "json",
        beforeSend: function () {
            $("#loading").show(); // 显示加载提示
        },
        success: function (data) {
            if(data.status == 200){
                // 成功获取数据
                var html = "";
                $(data.data).each(function (index, item) {
                    html += '<li>' + item.title + '</li>';
                });
                $("#list").append(html);
                last_id = data.last_id;
            } else {
                // 数据获取失败
                alert(data.message);
            }
        },
        complete: function () {
            $("#loading").hide(); // 隐藏加载提示
        },
        error: function () {
            alert("数据获取失败,请稍后重试");
        }
    });
}
Copy after login
  1. Use ThinkPHP6 to achieve the infinite scrolling effect

In When using the ThinkPHP6 framework, you need to define a controller to obtain data. You can refer to the following code:

<?php

namespace appcontroller;

use appBaseController;
use appmodelArticle;

class Index extends BaseController
{
    public function index()
    {
        $last_id = intval(input('post.last_id', 0));
        $articles = Article::where('id', '>', $last_id)->limit(10)->order('id', 'asc')->select();
        $data = [];
        foreach ($articles as $article) {
            $data[] = [
                'id' => $article->id,
                'title' => $article->title
            ];
        }
        return json(['status' => 200, 'data' => $data, 'last_id' => $articles->isEmpty() ? $last_id : $articles->last()->getId()]);
    }
}
Copy after login

When defining the controller, first introduce the corresponding Model, and then use the Model to obtain the data in the database. After obtaining the data, the data needs to be formatted into JSON format and then returned to the front end.

  1. Summary

By using the ThinkPHP6 framework and jQuery, we can easily achieve the infinite scroll effect. If your website needs to display a large amount of data, infinite scrolling is a good choice. It can reduce user click operations, improve user experience, increase user retention time, and promote website traffic growth.

The above is the detailed content of How to achieve infinite scrolling using ThinkPHP6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template