AJAX 实例

AJAX 实例(中文讲解)

本教程展示一个简单的 AJAX 实例,结合 Node.js、Express 和 MongoDB,实现用户数据的查询(GET 请求)和添加(POST 请求),数据以 JSON 格式交互。客户端使用 XMLHttpRequestfetch,结果显示在表格中。本例简洁实用,适合初学者理解 AJAX 的核心概念。


1. 实例概述

  • 目标:通过 AJAX 实现用户管理功能:
  • GET 请求:查询 MongoDB 中的用户列表,显示在页面表格。
  • POST 请求:提交新用户数据,存入 MongoDB。
  • 技术栈
  • 客户端:HTML + JavaScript(XMLHttpRequestfetch)。
  • 服务器:Node.js + Express。
  • 数据库:MongoDB,存储 JSON 格式数据。
  • 数据格式:JSON,用于前后端交互。

2. 环境准备

确保以下工具已安装:

  • Node.js:LTS 版本(如 v20.x),运行 node -v 检查。
  • MongoDB:本地运行或使用 MongoDB Atlas。
  • npm 依赖:Express 和 MongoDB 驱动。

安装依赖:

mkdir ajax-example
cd ajax-example
npm init -y
npm install express mongodb

MongoDB 数据准备:

use myDatabase
db.users.insertMany([
  { name: "张三", age: 25, hobbies: ["读书", "旅行"] },
  { name: "李四", age: 30, hobbies: ["编程", "运动"] }
])

3. 服务器端代码(Node.js + Express + MongoDB)

创建 server.js,实现与 MongoDB 的交互,返回 JSON 数据。

const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const uri = 'mongodb://localhost:27017/myDatabase';
const client = new MongoClient(uri);

app.use(express.json());
app.use(express.static('public'));
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST');
  next();
});

// 查询用户
app.get('/users', async (req, res) => {
  try {
    await client.connect();
    const db = client.db('myDatabase');
    const collection = db.collection('users');
    const users = await collection.find({}).toArray();
    res.json(users);
  } catch (error) {
    console.error('查询失败:', error);
    res.status(500).json({ error: '服务器错误' });
  } finally {
    await client.close();
  }
});

// 添加用户
app.post('/users', async (req, res) => {
  try {
    await client.connect();
    const db = client.db('myDatabase');
    const collection = db.collection('users');
    const user = req.body;
    if (!user.name || !user.age) {
      return res.status(400).json({ error: '姓名和年龄必填' });
    }
    const result = await collection.insertOne(user);
    res.json({ message: '添加成功', id: result.insertedId });
  } catch (error) {
    console.error('添加失败:', error);
    res.status(500).json({ error: '服务器错误' });
  } finally {
    await client.close();
  }
});

app.listen(3000, () => console.log('服务器运行在 http://localhost:3000'));
  • 说明
  • /users (GET):查询 MongoDB 的 users 集合,返回 JSON 数组。
  • /users (POST):接收 JSON 数据,插入新用户,返回成功消息。
  • CORS 允许跨域请求。
  • public 文件夹托管客户端 HTML。

4. 客户端代码(HTML + AJAX)

创建 public/index.html,使用 XMLHttpRequestfetch 与后端交互。

<!DOCTYPE html>
<html>
<head>
  <title>AJAX 示例</title>
  <style>
    table { border-collapse: collapse; margin-top: 10px; }
    th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
    button, input { padding: 10px; margin: 5px; }
  </style>
</head>
<body>
  <h1>用户管理</h1>
  <div>
    <input id="name" placeholder="姓名">
    <input id="age" type="number" placeholder="年龄">
    <button onclick="addUser()">添加用户(XMLHttpRequest)</button>
    <button onclick="addUserFetch()">添加用户(Fetch)</button>
  </div>
  <button onclick="loadUsers()">加载用户</button>
  <table id="userTable">
    <thead>
      <tr><th>姓名</th><th>年龄</th><th>爱好</th></tr>
    </thead>
    <tbody id="userList"></tbody>
  </table>
  <script>
    // XMLHttpRequest 加载用户
    function loadUsers() {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', 'http://localhost:3000/users', true);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            try {
              const users = JSON.parse(xhr.responseText);
              displayUsers(users);
            } catch (error) {
              document.getElementById('userList').innerHTML = `<tr><td colspan="3">错误:JSON 解析失败</td></tr>`;
            }
          } else {
            document.getElementById('userList').innerHTML = `<tr><td colspan="3">错误:${xhr.statusText} (${xhr.status})</td></tr>`;
          }
        }
      };
      xhr.onerror = function () {
        document.getElementById('userList').innerHTML = '<tr><td colspan="3">错误:网络错误</td></tr>';
      };
      xhr.send();
    }

    // XMLHttpRequest 添加用户
    function addUser() {
      const name = document.getElementById('name').value;
      const age = parseInt(document.getElementById('age').value);
      if (!name || !age) {
        alert('请输入姓名和年龄');
        return;
      }
      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://localhost:3000/users', true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            try {
              const response = JSON.parse(xhr.responseText);
              alert(response.message);
              loadUsers();
            } catch (error) {
              alert('错误:JSON 解析失败');
            }
          } else {
            alert(`添加失败:${xhr.statusText}`);
          }
        }
      };
      xhr.onerror = function () {
        alert('网络错误');
      };
      xhr.send(JSON.stringify({ name, age, hobbies: ['未知'] }));
    }

    // Fetch 添加用户
    async function addUserFetch() {
      const name = document.getElementById('name').value;
      const age = parseInt(document.getElementById('age').value);
      if (!name || !age) {
        alert('请输入姓名和年龄');
        return;
      }
      try {
        const response = await fetch('http://localhost:3000/users', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ name, age, hobbies: ['未知'] })
        });
        if (!response.ok) throw new Error(`服务器错误:${response.status}`);
        const result = await response.json();
        alert(result.message);
        loadUsers();
      } catch (error) {
        alert(`添加失败:${error.message}`);
      }
    }

    // 显示用户列表
    function displayUsers(users) {
      const userList = document.getElementById('userList');
      userList.innerHTML = '';
      if (users.length === 0) {
        userList.innerHTML = '<tr><td colspan="3">无用户数据</td></tr>';
        return;
      }
      users.forEach(user => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${user.name}</td>
          <td>${user.age}</td>
          <td>${user.hobbies ? user.hobbies.join(', ') : '无'}</td>
        `;
        userList.appendChild(row);
      });
    }
  </script>
</body>
</html>
  • 说明
  • 使用 <table> 显示用户数据,清晰直观。
  • loadUsers():通过 AJAX 获取用户列表,渲染表格。
  • addUser()addUserFetch():提交新用户,成功后刷新列表。
  • 处理 JSON 响应,显示错误信息。

5. 运行和测试

  1. 启动服务器
   node server.js
  1. 访问客户端
  • 打开浏览器,访问 http://localhost:3000
  • 点击“加载用户”,显示表格:
    姓名 年龄 爱好 张三 25 读书, 旅行 李四 30 编程, 运动
  • 输入姓名和年龄,点击“添加用户(XMLHttpRequest)”或“添加用户(Fetch)”,添加用户并刷新表格。
  1. 响应示例
  • GET /users
    json [ { "_id": "someObjectId1", "name": "张三", "age": 25, "hobbies": ["读书", "旅行"] }, { "_id": "someObjectId2", "name": "李四", "age": 30, "hobbies": ["编程", "运动"] } ]
  • POST /users
    json { "message": "添加成功", "id": "someObjectId3" }

6. JSON 在实例中的作用

  • 客户端
  • 发送:POST 请求使用 JSON.stringify() 将数据转为 JSON 字符串。
  • 接收:GET 响应通过 JSON.parse()(XMLHttpRequest)或 response.json()(fetch)解析。
  • 服务器
  • MongoDB 查询结果转为 JSON(res.json())。
  • POST 请求接收 JSON 数据,存入 MongoDB。
  • MongoDB:存储 JSON 格式文档,适合 AJAX 交互。

7. 注意事项与最佳实践

  1. 跨域处理
  • 本例使用 CORS(Access-Control-Allow-Origin: *)。
  • 生产环境限制域名:
    javascript res.header('Access-Control-Allow-Origin', 'http://trusted-domain.com');
  1. 错误处理
  • XMLHttpRequest:检查 xhr.statusonerror
  • fetch:检查 response.oktry-catch.
  • 服务器验证输入(nameage 必填)。
  1. JSON 安全
  • 客户端:用 try-catch 包裹 JSON.parse()
  • 服务器:验证 POST 数据,防止注入。
  1. 超时设置
  • XMLHttpRequest
    javascript xhr.timeout = 5000; xhr.ontimeout = () => alert('请求超时');
  • fetch
    javascript const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); fetch('http://localhost:3000/users', { signal: controller.signal });
  1. 推荐 fetch
  • fetch 语法简洁,基于 Promise,适合现代开发。
  • XMLHttpRequest 适用于特殊场景(如上传进度监控)。
  1. 性能优化
  • MongoDB 使用索引:
    javascript db.users.createIndex({ name: 1 });
  • 分页查询:
    javascript const users = await collection.find({}).skip(0).limit(10).toArray();
  1. 调试
  • 使用浏览器开发者工具(Network 面板)检查请求和响应。
  • 使用 JSON.stringify(data, null, 2) 格式化输出。

8. 总结

  • 实例功能:通过 AJAX 查询和添加 MongoDB 用户,渲染为表格。
  • 技术要点
  • XMLHttpRequest:使用 onreadystatechange 处理响应。
  • fetch:基于 Promise,解析 JSON 更简洁。
  • JSON 角色:前后端交互核心,JSON.stringify()JSON.parse() 关键。
  • 最佳实践:处理跨域、错误、超时,优先使用 fetch,优化数据库查询。

如果你需要其他功能(如删除、更新、分页、XML 响应),或想深入某部分,请告诉我,我会提供详细代码或指导!

const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const uri = 'mongodb://localhost:27017/myDatabase';
const client = new MongoClient(uri);

app.use(express.json());
app.use(express.static('public'));
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST');
  next();
});

app.get('/users', async (req, res) => {
  try {
    await client.connect();
    const db = client.db('myDatabase');
    const collection = db.collection('users');
    const users = await collection.find({}).toArray();
    res.json(users);
  } catch (error) {
    console.error('查询失败:', error);
    res.status(500).json({ error: '服务器错误' });
  } finally {
    await client.close();
  }
});

app.post('/users', async (req, res) => {
  try {
    await client.connect();
    const db = client.db('myDatabase');
    const collection = db.collection('users');
    const user = req.body;
    if (!user.name || !user.age) {
      return res.status(400).json({ error: '姓名和年龄必填' });
    }
    const result = await collection.insertOne(user);
    res.json({ message: '添加成功', id: result.insertedId });
  } catch (error) {
    console.error('添加失败:', error);
    res.status(500).json({ error: '服务器错误' });
  } finally {
    await client.close();
  }
});

app.listen(3000, () => console.log('服务器运行在 http://localhost:3000'));
<!DOCTYPE html>
<html>
<head>
  <title>AJAX 示例</title>
  <style>
    table { border-collapse: collapse; margin-top: 10px; }
    th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
    button, input { padding: 10px; margin: 5px; }
  </style>
</head>
<body>
  <h1>用户管理</h1>
  <div>
    <input id="name" placeholder="姓名">
    <input id="age" type="number" placeholder="年龄">
    <button onclick="addUser()">添加用户(XMLHttpRequest)</button>
    <button onclick="addUserFetch()">添加用户(Fetch)</button>
  </div>
  <button onclick="loadUsers()">加载用户</button>
  <table id="userTable">
    <thead>
      <tr><th>姓名</th><th>年龄</th><th>爱好</th></tr>
    </thead>
    <tbody id="userList"></tbody>
  </table>
  <script>
    function loadUsers() {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', 'http://localhost:3000/users', true);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            try {
              const users = JSON.parse(xhr.responseText);
              displayUsers(users);
            } catch (error) {
              document.getElementById('userList').innerHTML = `<tr><td colspan="3">错误:JSON 解析失败</td></tr>`;
            }
          } else {
            document.getElementById('userList').innerHTML = `<tr><td colspan="3">错误:${xhr.statusText} (${xhr.status})</td></tr>`;
          }
        }
      };
      xhr.onerror = function () {
        document.getElementById('userList').innerHTML = '<tr><td colspan="3">错误:网络错误</td></tr>';
      };
      xhr.send();
    }

    function addUser() {
      const name = document.getElementById('name').value;
      const age = parseInt(document.getElementById('age').value);
      if (!name || !age) {
        alert('请输入姓名和年龄');
        return;
      }
      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://localhost:3000/users', true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            try {
              const response = JSON.parse(xhr.responseText);
              alert(response.message);
              loadUsers();
            } catch (error) {
              alert('错误:JSON 解析失败');
            }
          } else {
            alert(`添加失败:${xhr.statusText}`);
          }
        }
      };
      xhr.onerror = function () {
        alert('网络错误');
      };
      xhr.send(JSON.stringify({ name, age, hobbies: ['未知'] }));
    }

    async function addUserFetch() {
      const name = document.getElementById('name').value;
      const age = parseInt(document.getElementById('age').value);
      if (!name || !age) {
        alert('请输入姓名和年龄');
        return;
      }
      try {
        const response = await fetch('http://localhost:3000/users', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ name, age, hobbies: ['未知'] })
        });
        if (!response.ok) throw new Error(`服务器错误:${response.status}`);
        const result = await response.json();
        alert(result.message);
        loadUsers();
      } catch (error) {
        alert(`添加失败:${error.message}`);
      }
    }

    function displayUsers(users) {
      const userList = document.getElementById('userList');
      userList.innerHTML = '';
      if (users.length === 0) {
        userList.innerHTML = '<tr><td colspan="3">无用户数据</td></tr>';
        return;
      }
      users.forEach(user => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${user.name}</td>
          <td>${user.age}</td>
          <td>${user.hobbies ? user.hobbies.join(', ') : '无'}</td>
        `;
        userList.appendChild(row);
      });
    }
  </script>
</body>
</html>

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注