Skip to content

AJAX ASP

服务器交互:实时搜索(概念示例)

Section titled “服务器交互:实时搜索(概念示例)”

异步 JavaScript 对于创建交互式用户体验非常强大,例如在用户输入时提供实时搜索建议。

本示例演示了使用 Fetch API 的客户端 JavaScript 和概念性的服务器端部分(这里通过简单的 Node.js/Express 和 PHP 代码段表示)。过时的 ASP Classic 示例已被移除。

这演示了网页如何与服务器端点通信,以便在用户在输入字段中输入字符时获取建议。

<p>**Start typing a name in the input field below:**</p>
<form onsubmit="return false;"> <!-- Prevent default submission -->
<label for="txtName">First name:</label>
<input type="text" id="txtName" name="name" autocomplete="off">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<p><small>Server endpoint: /api/suggestions</small></p>
const nameInput = document.getElementById('txtName');
const hintSpan = document.getElementById('txtHint');
let debounceTimer; // For debouncing requests
async function showHint(query) {
// Basic validation
if (query.length === 0) {
hintSpan.innerHTML = '';
return;
}
hintSpan.innerHTML = '<i>Searching...</i>'; // Provide feedback
try {
// Construct the URL with the query parameter
const url = `/api/suggestions?q=${encodeURIComponent(query)}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const suggestions = await response.json(); // Expecting JSON array of strings
if (suggestions.length > 0) {
// Sanitize suggestions before displaying (basic example)
const safeSuggestions = suggestions.map(s =>
String(s).replace(/</g, "&lt;").replace(/>/g, "&gt;")
);
hintSpan.innerHTML = safeSuggestions.join(', ');
} else {
hintSpan.innerHTML = 'no suggestion';
}
} catch (error) {
console.error('Error fetching suggestions:', error);
hintSpan.innerHTML = '<i style="color:red;">Error fetching suggestions</i>';
}
}
nameInput.addEventListener('input', (event) => {
const query = event.target.value;
// Debounce: Clear the previous timer and set a new one
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
showHint(query);
}, 300); // Wait 300ms after user stops typing
});
  • 事件监听器:一个 input 事件监听器附加到文本字段上。当值改变时触发。
  • 防抖 (Debouncing):使用 setTimeout(防抖)机制来防止在每次击键时都发送请求。它会等到用户暂停输入一段短暂时间(例如 300ms)后才发送。
  • showHint 函数:这个 async 函数处理逻辑。
  • 输入检查:它检查输入字段是否为空;如果为空,则清除提示并返回。
  • 反馈:它向用户提供 ‘Searching…’ 反馈。
  • Fetch 请求:它使用 fetch 向服务器端点(例如,/api/suggestions)发起一个 GET 请求,并将用户的输入(query)作为 URL 参数(?q=...)。encodeURIComponent 确保查询安全地包含在 URL 中。
  • 错误处理:它包含 try...catch 并检查 response.ok 以实现健壮的错误管理。
  • JSON 解析:它期望服务器返回 JSON 响应(一个字符串建议数组),并使用 response.json() 进行解析。
  • 显示结果:它使用建议(用逗号分隔)更新 txtHint span,或者显示 ‘no suggestion’。包含了基本的清理(replace(/</g, "&lt;"))作为对抗 HTML 注入的最小安全措施,尽管服务器端验证/清理至关重要。
  1. 接收请求并提取查询参数(例如,‘q’)。
  2. 根据查询执行查找(例如,查询数据库、搜索内存中的列表)。
  3. 将结果格式化为 JSON 数组。
  4. 将 JSON 响应发送回客户端。
// --- Server-Side (Node.js with Express) ---
const express = require('express');
const app = express();
const port = 3000;
// Sample data (in a real app, this would likely come from a database)
const names = [
"Anna", "Amanda", "Alice", "Bob", "Brittany", "Barbara",
"Charles", "Cindy", "Cinderella", "David", "Diana", "Doris", // ... more names
];
app.get('/api/suggestions', (req, res) => {
const query = (req.query.q || '').toLowerCase(); // Get 'q' query param, default to empty string
let suggestions = [];
if (query.length > 0) {
suggestions = names.filter(name =>
name.toLowerCase().startsWith(query)
);
}
// Set content type to JSON and send the array
res.setHeader('Content-Type', 'application/json');
res.json(suggestions);
});
app.listen(port, () => {
console.log(`Suggestion API listening at http://localhost:${port}`);
});
<?php
// --- Server-Side (PHP - e.g., get_suggestions.php) ---
// Sample data (replace with database query in real application)
$names = [
"Anna", "Amanda", "Alice", "Bob", "Brittany", "Barbara",
"Charles", "Cindy", "Cinderella", "David", "Diana", "Doris", // ... more names
];
$query = isset($_GET['q']) ? strtolower($_GET['q']) : '';
$suggestions = [];
if (!empty($query)) {
foreach ($names as $name) {
// Simple case-insensitive starts-with check
if (strpos(strtolower($name), $query) === 0) {
$suggestions[] = $name;
}
}
}
// Set header to indicate JSON response
header('Content-Type: application/json');
// Encode the array as JSON and output it
echo json_encode($suggestions);
?>

重要提示: 这些服务器端示例经过了简化。实际应用需要进行适当的输入验证、清理、错误处理、可能更高效的数据库查询以及安全方面的考虑。