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:
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.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 <!DOCTYPE html>
<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 函数放在这里
// ... (此处省略函数的重复代码) ...
// 页面加载完成后立即