2025-05-24 09:38:22 +08:00

121 lines
3.5 KiB
JavaScript

const searchBtn = document.getElementById("searchBtn");
const input = document.getElementById("searchInput");
const resultBox = document.getElementById("results");
let currentPage = 1;
let totalPages = 1;
let lastKeywords = [];
function showLoading() {
resultBox.innerHTML = "<li>加载中...</li>";
}
function renderPagination() {
const pagination = document.createElement("div");
pagination.className = "pagination";
if (currentPage > 1) {
const prevBtn = document.createElement("button");
prevBtn.textContent = "上一页";
prevBtn.onclick = () => fetchResults(lastKeywords, currentPage - 1);
pagination.appendChild(prevBtn);
}
if (currentPage < totalPages) {
const nextBtn = document.createElement("button");
nextBtn.textContent = "下一页";
nextBtn.onclick = () => fetchResults(lastKeywords, currentPage + 1);
pagination.appendChild(nextBtn);
}
resultBox.appendChild(pagination);
}
async function fetchResults(keywords, page) {
currentPage = page;
lastKeywords = keywords;
const keywordGroups = keywords.map(k => [k]);
const requestBody = {
keywordGroups,
page: currentPage,
size: 10
};
console.log("[INFO] 请求地址: http://app.wisdompulse.cn/search");
console.log("[INFO] 请求方法: POST");
console.log("[INFO] 请求体:", JSON.stringify(requestBody, null, 2));
showLoading();
try {
const response = await fetch("http://app.wisdompulse.cn/search", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(requestBody)
});
console.log("[INFO] 响应状态:", response.status, response.statusText);
const data = await response.json();
console.log("[INFO] 响应体:", data);
resultBox.innerHTML = "";
if (!data.results || data.results.length === 0) {
console.log("[INFO] 未返回结果数据");
resultBox.innerHTML = "<li>未找到相关文档</li>";
return;
}
totalPages = Math.ceil(data.total / data.size);
data.results.forEach(doc => {
const li = document.createElement("li");
const cleanPath = doc.filepath.replace(/^import-data\//, "").replace(/\.md$/, ".html");
const link = document.createElement("a");
link.href = `http://share.wisdompulse.cn/public/${cleanPath}`;
link.target = "_blank";
link.textContent = doc.filename;
const snippet = document.createElement("div");
snippet.className = "summary";
snippet.innerHTML = doc.summary?.slice(0, 300) + "...";
li.appendChild(link);
li.appendChild(snippet);
resultBox.appendChild(li);
});
renderPagination();
} catch (err) {
console.error("[ERROR] 搜索失败:", err);
resultBox.innerHTML = "<li>搜索失败,请检查网络或服务状态。</li>";
}
}
function triggerSearch() {
const inputValue = input.value.trim();
console.log("[INFO] 用户输入关键词:", inputValue);
if (!inputValue) {
console.warn("[WARN] 输入为空");
return;
}
const keywords = inputValue.split(/\s+/).filter(Boolean);
fetchResults(keywords, 1);
}
searchBtn.addEventListener("click", triggerSearch);
// 支持按回车键直接搜索
input.addEventListener("keydown", e => {
if (e.key === "Enter") {
triggerSearch();
}
});