When displaying a large number of documents on the website front-end, pagination navigation is a key feature to improve 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.archive/listin the interfacepageandtotalParameter, build a comprehensive 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/listThe interface. 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 special attention:
type="page": This is the basis for obtaining pagination information. When you set in the request,typeresponse forpagethen, the interface of Anq CMS will return the document data of the current page(data),还会额外返回一个total字段,它包含了符合当前查询条件的所有文档的总数量。如果未设置此参数或设置为其他值(如list),则不会返回total.pageandlimit:pageThe parameter specifies the page number of the content you want to retrieve.limitThe parameter defines how many documents are displayed per page.
By cleverly coordinating 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.We need to display a list of articles under a certain category, with 10 articles per page.
第一步:Initiate API request and retrieve data
Firstly, your frontend application needs to send a request to the API interface of Anqi CMS. This request will include the information mentioned previouslytype/pageandlimitParameters, as well as 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'sfetchAPI sends a request to AnQi CMS and retrieves information from the responsedata(current page document list) andtotal(total number of documents).
Step two: calculate the total number of pages and build the pagination navigation UI
Get tototalDocuments(Total number of documents)after that, combiningitemsPerPage(Number of items per page),we can calculate the total number of pages, and based on this, 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('');
}
the aboverenderPaginationIn the function, we first calculate the total number of pagestotalPages。Then, we dynamically generated the "HomefetchDocumentsFunction, and pass in the newpageParameters, you can reload the document data of the corresponding page.
In order to provide a better user experience, we also addeddisabledandactiveClass name, so that the current page and non-clickable buttons can be distinguished by CSS styles (for example, disable "Previous page" when 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 函数放在这里
// ... (此处省略函数的重复代码) ...
// 页面加载完成后立即