From 127654a558e1c1442f273952b42fd9003dbff476 Mon Sep 17 00:00:00 2001 From: hz4th_coder Date: Tue, 14 Jul 2026 00:40:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=90=9C=E7=B4=A2=E5=88=86?= =?UTF-8?q?=E9=A1=B5=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 后端搜索API支持offset参数,返回总数用于分页 - 前端传递offset参数实现正确分页 --- routes/articles.py | 14 +++++++++----- static/js/library.js | 4 ++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/routes/articles.py b/routes/articles.py index 1477042..a135d92 100644 --- a/routes/articles.py +++ b/routes/articles.py @@ -31,16 +31,20 @@ def search_articles(): """搜索文章""" keyword = request.args.get('q', '') category = request.args.get('category') - limit = request.args.get('limit', type=int) # 支持limit参数 + limit = request.args.get('limit', type=int) + offset = request.args.get('offset', 0, type=int) if not keyword: return jsonify({'error': '请提供搜索关键词'}), 400 - articles = db.search_articles(keyword, category) + all_articles = db.search_articles(keyword, category) + total_count = len(all_articles) - # 如果有limit参数,截取 + # 分页截取 if limit: - articles = articles[:limit] + articles = all_articles[offset:offset + limit] + else: + articles = all_articles # 解析JSON字段 for article in articles: @@ -50,7 +54,7 @@ def search_articles(): return jsonify({ 'success': True, 'articles': articles, - 'count': len(articles) + 'count': total_count # 返回总数,用于分页 }) @bp.route('/', methods=['GET']) diff --git a/static/js/library.js b/static/js/library.js index 252087c..9fd53bd 100644 --- a/static/js/library.js +++ b/static/js/library.js @@ -49,10 +49,10 @@ async function loadArticles() { }); if (keyword) { - // 搜索时也传递 limit 参数 + // 搜索时也传递 limit 和 offset 参数 let searchUrl = `${API_BASE}/api/articles/search?q=${encodeURIComponent(keyword)}`; if (category) searchUrl += `&category=${encodeURIComponent(category)}`; - searchUrl += `&limit=${pageSize}`; + searchUrl += `&limit=${pageSize}&offset=${(currentPage - 1) * pageSize}`; const response = await fetch(searchUrl); const data = await response.json();