上一篇
最新动态 📢
根据2025年7月StackOverflow开发者调查报告显示,近89%的Web项目仍在使用AJAX进行前后端数据交互,其中JSON格式占比高达92%!今天我们就来手把手实现这个经典场景~
假设我们正在开发一个用户管理系统,需要:
[用户输入] → [AJAX请求] → [后端查询] → [返回JSON] → [页面渲染]
<div class="search-box"> <h3>🔍 用户查询系统</h3> <input type="text" id="username" placeholder="输入用户名"> <button onclick="searchUser()">搜索</button> </div> <div id="result" class="result-area"> <!-- 结果将在这里动态显示 --> </div>
async function searchUser() { const username = document.getElementById('username').value; try { const response = await fetch('/api/search', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username }) }); if (!response.ok) throw new Error('查询失败'); const data = await response.json(); renderResults(data); } catch (error) { console.error('出错啦:', error); document.getElementById('result').innerHTML = `<div class="error">😵 ${error.message}</div>`; } } function renderResults(users) { const resultDiv = document.getElementById('result'); if (users.length === 0) { resultDiv.innerHTML = '<div>🕵️ 没有找到匹配用户</div>'; return; } let html = '<ul class="user-list">'; users.forEach(user => { html += ` <li> <strong>${user.name}</strong> <span>邮箱: ${user.email}</span> <span>注册时间: ${new Date(user.create_time).toLocaleDateString()}</span> </li> `; }); html += '</ul>'; resultDiv.innerHTML = html; }
// 假设使用MySQL数据库 const mysql = require('mysql2/promise'); const pool = mysql.createPool({ host: 'localhost', user: 'root', password: 'yourpassword', database: 'user_db' }); app.post('/api/search', async (req, res) => { try { const { username } = req.body; const [rows] = await pool.query( `SELECT id, name, email, create_time FROM users WHERE name LIKE ?`, [`%${username}%`] ); res.json(rows); } catch (err) { console.error('数据库查询错误:', err); res.status(500).json({ error: '服务器内部错误' }); } });
<?php header('Content-Type: application/json'); $username = $_POST['username'] ?? ''; $pdo = new PDO('mysql:host=localhost;dbname=user_db', 'root', 'yourpassword'); try { $stmt = $pdo->prepare("SELECT id, name, email, create_time FROM users WHERE name LIKE ?"); $stmt->execute(["%$username%"]); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($results); } catch (PDOException $e) { http_response_code(500); echo json_encode(['error' => '数据库查询失败']); } ?>
CORS处理
如果是跨域请求,后端需要设置:
res.setHeader('Access-Control-Allow-Origin', '*');
SQL防注入
务必使用参数化查询(如示例中的占位符)
错误处理
性能优化
let searchTimer; function onInputChange() { clearTimeout(searchTimer); searchTimer = setTimeout(searchUser, 300); }
可选链操作符的广泛使用:
const email = data.users?.[0]?.email ?? '暂无';
WebSocket的补充使用:
TypeScript成为主流:
interface User { id: number; name: string; email: string; create_time: string; } async function searchUser(): Promise<User[]> { // ... }
🎉
这个经典的AJAX查询模式在2025年依然焕发活力!关键是要处理好安全性、错误边界和用户体验,现在就去实现你的数据查询功能吧!遇到问题记得——console.log是你的好朋友~ 👨💻
(本文示例代码经过简化,实际项目请根据需求调整)
本文由 占胤雅 于2025-07-31发表在【云服务器提供商】,文中图片由(占胤雅)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/496867.html
发表评论