documentgetElementByIdbtnQueryaddEventListenerclick = const key = documentgetElementByIdkeyvalue; axios url httplocalhost3000apiblogssearch method get data id k
要完善查询功能,可以在点击查询按钮时,根据输入的关键词查询符合条件的博客文章。可以按照以下步骤进行修改:
- 修改HTML代码,给查询按钮添加id属性,用于获取按钮元素。
<button id="btnQuery">查询</button>
- 修改JavaScript代码,将查询功能的逻辑添加到点击事件的回调函数中。获取关键词输入框的值,然后使用axios发送GET请求到服务器的查询接口,并传递关键词参数。接收返回的结果,根据结果生成HTML字符串并更新到页面中。
document.getElementById("btnQuery").addEventListener("click",() => {
const key = document.getElementById("key").value;
axios({
url: "http://localhost:3000/api/blogs/search",
method: "get",
params: {
key: key
}
}).then(results => {
const blogList = results.data.data;
const htmlStr = blogList.map((item, index) => {
return `<tr>
<td>${index + 1}</td>
<td>${item.title}</td>
<td>${item.author}</td>
<td>${item.classify}</td>
<td>
<input type="button" value="删除" onclick="del(${item.id})">
</td>
</tr>`;
}).join('');
document.getElementById("blogs").innerHTML = htmlStr;
});
})
- 修改服务器端的查询接口,根据传递的关键词参数进行查询,并返回符合条件的博客文章列表。
app.get('/api/blogs/search', (req, res) => {
const { key } = req.query;
const results = blogs.filter(blog => {
return (
blog.id.toString().includes(key) ||
blog.title.includes(key) ||
blog.author.includes(key) ||
blog.classify.includes(key)
);
});
res.json({ data: results });
});
注意:修改服务器端代码后,需要重新启动服务器才能生效
原文地址: https://www.cveoy.top/t/topic/h2G0 著作权归作者所有。请勿转载和采集!