How to build pagination navigation for AnQiCMS document list on the front-end page (using `page` and `total` parameters)?

Calendar 👁️ 65

When displaying a large number of documents on the front end of a website, pagination navigation is a key function to enhance user experience and manage data loading efficiency.AnQiCMS (AnQiCMS) provides a powerful and flexible API interface, allowing you to easily implement pagination functionality for document lists on the front end.This article will introduce how to usearchive/listthe interface inpageandtotalParameters, build a functionally complete pagination navigation.


Understand the core of AnQi CMS pagination mechanism

To build the pagination navigation of the document list, we mainly rely on AnQi CMS.archive/listInterface. This interface can not only obtain document data but also return the total number of documents under certain conditions, which is the key information we need to build pagination navigation.

Here are two core parameters that need to be paid special attention to:

  1. type="page"This is the basis for obtaining pagination information. When you settypeWithpageThe Anq CMS interface will return the document data of the current page(dataIt will also return an extra onetotalField, it contains the total number of documents that match the current query conditions. If this parameter is not set or set to other values (such aslist), it will not returntotal.
  2. pageandlimit:
    • pageThe parameter specifies the page of content you want to retrieve.
    • limitThe parameter defines how many documents are displayed per page.

By the clever combination of these three parameters, we can obtain all the data needed to build pagination from the backend.

Steps to implement pagination navigation on the frontend.

Next, let's take a typical scenario as an example and explain in detail how to build pagination navigation on the front end.Assuming we need to display a list of articles under a certain category, with 10 articles per page.

The first step: initiate the API request and obtain the data

Firstly, your frontend application needs to send a request to the AnQi CMS API interface. This request will include the information we mentioned previouslytype/pageandlimitThe parameter, and other filtering conditions you may need, such asmoduleId(Model ID) andcategoryId(Category ID).

async function fetchDocuments(currentPage = 1, itemsPerPage = 10, categoryId = 1) {
    const domain = 'https://yourdomain.com'; // 替换为您的域名
    const apiUrl = `${domain}/api/archive/list`;

    // 构建请求参数
    const params = new URLSearchParams({
        moduleId: 1, // 假设文章模型ID为1
        categoryId: categoryId,
        type: 'page', // 关键:获取total总数
        page: currentPage,
        limit: itemsPerPage
    });

    try {
        const response = await fetch(`${apiUrl}?${params.toString()}`);
        const result = await response.json();

        if (result.code === 0) {
            const documents = result.data; // 当前页的文档列表
            const totalDocuments = result.total; // 符合条件的总文档数量

            // 在这里处理文档列表和总数
            console.log('当前页文档:', documents);
            console.log('总文档数量:', totalDocuments);

            // 调用函数构建分页导航
            renderPagination(currentPage, itemsPerPage, totalDocuments, categoryId);
            // 调用函数渲染文档列表
            renderDocumentList(documents);

        } else {
            console.error('获取文档列表失败:', result.msg);
        }
    } catch (error) {
        console.error('请求发生错误:', error);
    }
}

// 示例调用,获取分类ID为1的第一页文章,每页10条
fetchDocuments(1, 10, 1);

This code demonstrates how to use JavaScript'sfetchThe API sends a request to AnQi CMS and retrieves the responsedataand the document list on the current pagetotal(Total number of documents).

Step two: Calculate the total number of pages and build the pagination navigation UI

obtaining tototalDocumentsAfter combining the total number of documentsitemsPerPageWith the number of documents displayed per page, we can calculate the total number of pages and accordingly generate the HTML structure for pagination navigation.

function renderPagination(currentPage, itemsPerPage, totalDocuments, categoryId) {
    const totalPages = Math.ceil(totalDocuments / itemsPerPage); // 计算总页数
    const paginationContainer = document.getElementById('pagination-container'); // 假设页面中有这个元素来承载分页

    if (!paginationContainer) return; // 如果没有找到容器,则不渲染

    let paginationHtml = '';

    // 生成“首页”和“上一页”按钮
    paginationHtml += `<a href="#" onclick="fetchDocuments(1, ${itemsPerPage}, ${categoryId})" ${currentPage === 1 ? 'class="disabled"' : ''}>首页</a>`;
    paginationHtml += `<a href="#" onclick="fetchDocuments(${currentPage - 1}, ${itemsPerPage}, ${categoryId})" ${currentPage === 1 ? 'class="disabled"' : ''}>上一页</a>`;

    // 生成页码链接(这里为了简化,只显示部分页码)
    const maxPageLinks = 5; // 最多显示5个页码
    let startPage = Math.max(1, currentPage - Math.floor(maxPageLinks / 2));
    let endPage = Math.min(totalPages, startPage + maxPageLinks - 1);

    if (endPage - startPage + 1 < maxPageLinks) {
        startPage = Math.max(1, endPage - maxPageLinks + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
        paginationHtml += `<a href="#" onclick="fetchDocuments(${i}, ${itemsPerPage}, ${categoryId})" ${currentPage === i ? 'class="active"' : ''}>${i}</a>`;
    }

    // 生成“下一页”和“尾页”按钮
    paginationHtml += `<a href="#" onclick="fetchDocuments(${currentPage + 1}, ${itemsPerPage}, ${categoryId})" ${currentPage === totalPages ? 'class="disabled"' : ''}>下一页</a>`;
    paginationHtml += `<a href="#" onclick="fetchDocuments(${totalPages}, ${itemsPerPage}, ${categoryId})" ${currentPage === totalPages ? 'class="disabled"' : ''}>尾页</a>`;

    paginationContainer.innerHTML = paginationHtml;
}

// 示例函数:渲染文档列表(根据您的模板结构自行实现)
function renderDocumentList(documents) {
    const documentListContainer = document.getElementById('document-list'); // 假设页面中有这个元素
    if (!documentListContainer) return;
    documentListContainer.innerHTML = documents.map(doc => `
        <div class="document-item">
            <h3><a href="${doc.link || '#'}">${doc.title}</a></h3>
            <p>${doc.description || ''}</p>
            <small>发布时间: ${new Date(doc.created_time * 1000).toLocaleDateString()}</small>
        </div>
    `).join('');
}

In the aboverenderPaginationIn the function, we first calculate the total number of pagestotalPages. Then, we dynamically generated the "home", "previous page", specific page number links, "next page", and "end page" buttons. When the user clicks on these links, by callingfetchDocumentsA function, and pass in a newpageParameters, you can reload the document data of the corresponding page.

In order to provide a better user experience, we also addeddisabledandactiveClass name to differentiate the current page from non-clickable buttons (for example, disable "Previous page" on the first page).

Step 3: Page loading and event handling

To display the first page content and pagination navigation when the page is initially loaded, you can call it after the page is loadedfetchDocumentsFunction.

`html &lt;!DOCTYPE html&gt;

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>安企CMS文档列表</title>
<style>
    .pagination a {
        display: inline-block;
        padding: 8px 16px;
        margin: 0 4px;
        border: 1px solid #ddd;
        text-decoration: none;
        color: #337ab7;
        border-radius: 4px;
    }
    .pagination a.active {
        background-color: #337ab7;
        color: white;
        border: 1px solid #337ab7;
    }
    .pagination a.disabled {
        color: #ccc;
        pointer-events: none;
        cursor: default;
    }
    .document-item {
        border-bottom: 1px dashed #eee;
        padding: 10px 0;
        margin-bottom: 10px;
    }
</style>

<h1>文章列表</h1>
<div id="document-list">
    <!-- 文档列表将在这里加载 -->
    加载中...
</div>
<div id="pagination-container" class="pagination">
    <!-- 分页导航将在这里加载 -->
</div>

<script>
    // 上文的 fetchDocuments, renderPagination, renderDocumentList 函数放在这里
    // ... (此处省略函数的重复代码) ...

    // 页面加载完成后立即

Related articles

In the AnQiCMS document list, what do the `images`, `logo`, and `thumb` fields represent, and how should they be used?

When using AnQi CMS to manage website content, we often encounter scenarios involving image upload and display.In the data structure of documents (articles, products, etc.), categories, and even single pages, the `images`, `logo`, and `thumb` fields play different roles. They work together to support the effective presentation and performance optimization of the website's visual content.Understanding their specific purposes can help us better plan content and optimize the user experience.### `images` : multi-image display and rich content `images`

2025-11-09

How to handle the `extra` field returned by the `archive/list` interface to obtain custom field information?

When using AnQi CMS for website content management, we often need to display more personalized data beyond the usual information such as title, summary, thumbnail, etc.This additional information, such as the author of the article, the model of the product, the release location, etc., is achieved through the powerful custom field function of Anqi CMS.How can we elegantly extract and utilize these custom fields when we obtain the document list through the `archive/list` interface on the front end?The answer is hidden in the `extra` field of the returned data

2025-11-09

How to use the `q` parameter to perform keyword search in the AnQiCMS document list and realize the in-site search function?

In the daily operation of a website, providing users with an efficient and convenient in-site search function is a key factor in improving user experience and guiding content discovery.For those of us using AnQiCMS to manage website content, it is not difficult to achieve this function.AnQi CMS provides a very practical parameter——`q`, which allows us to easily search for keywords in the document list.### Start the in-site search journey: Understanding the `q` parameter In the AnQiCMS document list interface (/api/archive/list), `q`

2025-11-09

How does the `child=false` parameter affect the display of categories and their subcategories when retrieving the document list?

In Anqi CMS, the `archive/list` interface is the core tool for obtaining the list of website documents, which provides a variety of parameters to help us accurately filter and display content.Among them, the `child` parameter, although simple in appearance, plays a vital role in the display of categories and their subcategories in documents, directly affecting the granularity of content presentation.Understand and make good use of this parameter, it can make the content organization of your website clearer and improve the user experience.By default, when you access `archive/list`

2025-11-09

How to use the `type=related` mode in the AnQiCMS document list interface to get related articles?

In website content operation, providing users with relevant article recommendations is an important strategy to enhance user experience, extend visit duration, and optimize content discovery.The AnqiCMS document list interface (`archive/list`) provides a very convenient feature, which can be easily achieved by setting the `type=related` parameter.### Understanding the `type=related` mode After a user has finished browsing a document (article, product, etc.), they usually want to find more information that is thematically similar and complementary to the current content.

2025-11-09

Is the `created_time` and `updated_time` returned by the AnQiCMS document list a Unix timestamp, and how do I convert it to a readable date?

When using AnQiCMS, we often retrieve detailed information or lists of documents or other content from the API interface.In these returned data, `created_time` (creation time) and `updated_time` (update time) are two very critical fields.Many users may be curious, what are these values that look like a string of numbers?They are actually standard Unix timestamps. ### Understanding Unix Timestamps Unix timestamp, also known as Posix time

2025-11-09

How to determine the visibility or review status of the document from the `archive/list` interface?

In AnQi CMS, one of the core aspects of content management is the control of document status, which directly relates to the visibility and review process of website content.When you retrieve the document list through the `archive/list` interface, the `status` field in the returned data assumes this critical responsibility.Understanding the meaning of this field can help you manage website content more efficiently and ensure that information is presented correctly to visitors.### `status` field

2025-11-09

How to combine the filtering conditions obtained from `archiveFilters.md` and apply them to the custom filtering parameters of `archive/list`?

In Anqi CMS, efficiently managing and displaying website content is the key to improving user experience.When the amount of content grows, providing flexible filtering functions is particularly important to help visitors quickly find the information they need.The AQ CMS provides powerful API interface support, by cleverly combining the filtering conditions obtained from the `archive/filters` interface and applying them to the custom filtering parameters of the `archive/list` interface, we can build extremely practical content filtering functionality.###

2025-11-09