indexhtmldiv id=top div input type=text id=key style=width 400px; placeholder=请输入要查找的博客标题、作者、分类等关键字input id=btnQuery type=button value=查找 div
首先,在index.html文件中的按钮上添加一个点击事件,调用查询函数:
<input id="btnQuery" type="button" value="查找" onclick="searchBlogs()">
接下来,在index.js文件中添加查询函数,并使用axios发送请求:
function searchBlogs() {
const key = document.getElementById("key").value;
axios({
url: "http://localhost:3000/api/blogs/search",
method: "post",
data: {
id: key,
title: key,
author: key,
classify: 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;
});
}
最后,在node.js的API文件中添加查询函数的处理逻辑:
exports.getSearchBlogs = (req, res) => {
const info = req.body;
const key = `%${info.key}%`;
const sqlStr = `select * from blogs_info where id LIKE ? or title LIKE ? or author LIKE ? or classify LIKE ?`;
db.query(sqlStr, [key, key, key, key], (err, results) => {
if (err) return res.cc(err);
if (results.length === 0) return res.cc("查询文章失败,该文章不存在");
res.send({
status: 200,
message: "查询成功",
data: results
});
});
};
以上代码将在点击查询按钮时,根据输入的关键字发送请求到API,然后根据查询结果动态生成展示结果的HTML代码,并更新到网页中
原文地址: https://www.cveoy.top/t/topic/h2FE 著作权归作者所有。请勿转载和采集!