Compare commits

..
1 Commits
Author SHA1 Message Date
hz4th_coder 127654a558 修复搜索分页功能
- 后端搜索API支持offset参数,返回总数用于分页
- 前端传递offset参数实现正确分页
2026-07-14 00:40:40 +08:00
2 changed files with 11 additions and 7 deletions
+9 -5
View File
@@ -31,16 +31,20 @@ def search_articles():
"""搜索文章""" """搜索文章"""
keyword = request.args.get('q', '') keyword = request.args.get('q', '')
category = request.args.get('category') 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: if not keyword:
return jsonify({'error': '请提供搜索关键词'}), 400 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: if limit:
articles = articles[:limit] articles = all_articles[offset:offset + limit]
else:
articles = all_articles
# 解析JSON字段 # 解析JSON字段
for article in articles: for article in articles:
@@ -50,7 +54,7 @@ def search_articles():
return jsonify({ return jsonify({
'success': True, 'success': True,
'articles': articles, 'articles': articles,
'count': len(articles) 'count': total_count # 返回总数,用于分页
}) })
@bp.route('/<int:article_id>', methods=['GET']) @bp.route('/<int:article_id>', methods=['GET'])
+2 -2
View File
@@ -49,10 +49,10 @@ async function loadArticles() {
}); });
if (keyword) { if (keyword) {
// 搜索时也传递 limit 参数 // 搜索时也传递 limit 和 offset 参数
let searchUrl = `${API_BASE}/api/articles/search?q=${encodeURIComponent(keyword)}`; let searchUrl = `${API_BASE}/api/articles/search?q=${encodeURIComponent(keyword)}`;
if (category) searchUrl += `&category=${encodeURIComponent(category)}`; if (category) searchUrl += `&category=${encodeURIComponent(category)}`;
searchUrl += `&limit=${pageSize}`; searchUrl += `&limit=${pageSize}&offset=${(currentPage - 1) * pageSize}`;
const response = await fetch(searchUrl); const response = await fetch(searchUrl);
const data = await response.json(); const data = await response.json();