要实现根据用户输入查询数据库并在另一个页面显示结果的功能,通常涉及以下几个步骤和技术概念:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search Page</title>
</head>
<body>
<input type="text" id="searchInput" placeholder="Enter search term">
<button onclick="search()">Search</button>
<script>
async function search() {
const searchTerm = document.getElementById('searchInput').value;
const response = await fetch('/api/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query: searchTerm })
});
const data = await response.json();
window.location.href = '/results.html?data=' + encodeURIComponent(JSON.stringify(data));
}
</script>
</body>
</html>
const express = require('express');
const mysql = require('mysql');
const app = express();
app.use(express.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'database_name'
});
db.connect(err => {
if (err) throw err;
console.log('Database connected!');
});
app.post('/api/search', (req, res) => {
const query = req.body.query;
const sql = `SELECT * FROM table_name WHERE column_name LIKE '%${query}%'`;
db.query(sql, (err, results) => {
if (err) throw err;
res.json(results);
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search Results</title>
</head>
<body>
<h1>Search Results</h1>
<ul id="results"></ul>
<script>
const data = JSON.parse(decodeURIComponent(new URLSearchParams(window.location.search).get('data')));
const resultsList = document.getElementById('results');
data.forEach(item => {
const li = document.createElement('li');
li.textContent = item.column_name;
resultsList.appendChild(li);
});
</script>
</body>
</html>
通过以上步骤和代码示例,你可以实现一个基本的搜索功能,并在另一个页面显示查询结果。
领取专属 10元无门槛券
手把手带您无忧上云