AJAX 技术

异步 JavaScript 和 XML - 创建动态网页的强大技术

什么是 AJAX?

AJAX(Asynchronous JavaScript and XML)是一种创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

异步通信

在不阻塞用户界面的情况下与服务器交换数据,提供流畅的用户体验。

🔄

局部更新

只更新页面需要变化的部分,减少数据传输量,提高响应速度。

🎯

动态交互

创建响应式的用户界面,实现实时数据更新和交互功能。

AJAX 的核心组件

  • XMLHttpRequest 对象:AJAX 的核心技术,用于在后台与服务器交换数据
  • JavaScript:用于创建和处理 AJAX 请求
  • DOM:用于更新网页内容
  • CSS:用于美化动态更新的内容

创建第一个 AJAX 请求

下面是一个基本的 AJAX 请求示例,使用 XMLHttpRequest 对象:

// 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();

// 配置请求
xhr.open('GET', 'https://api.example.com/data', true);

// 设置回调函数
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // 请求成功,处理响应数据
        const response = JSON.parse(xhr.responseText);
        console.log(response);
    }
};

// 发送请求
xhr.send();

readyState 和 status

XMLHttpRequest 对象的 readyState 属性表示请求的状态:

  • 0:请求未初始化
  • 1:服务器连接已建立
  • 2:请求已接收
  • 3:请求处理中
  • 4:请求已完成,且响应已就绪

HTTP status 表示请求的结果状态:

  • 200:请求成功
  • 404:未找到资源
  • 500:服务器内部错误

在线演示:GET 请求

使用 Fetch API

Fetch API 是现代浏览器提供的更强大的 AJAX 接口,使用 Promise 处理异步操作:

// 使用 Fetch API
fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
    });

// 使用 async/await 语法
async function fetchData() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error:', error);
    }
}

发送 POST 请求

POST 请求用于向服务器发送数据:

// 发送 JSON 数据
const data = {
    name: 'John',
    email: 'john@example.com'
};

fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch((error) => console.error('Error:', error));

在线演示:POST 请求

实际应用场景

📊

实时数据更新

股票价格、天气预报等实时数据更新,无需刷新页面。

💬

聊天应用

即时消息发送和接收,实现实时通信功能。

🛒

电子商务

购物车更新、订单提交、支付处理等。

📝

表单验证

实时验证用户输入,提供即时反馈。

搜索建议示例

这是一个常见的 AJAX 应用:搜索时显示建议列表。

const searchInput = document.getElementById('search');
const suggestions = document.getElementById('suggestions');

searchInput.addEventListener('input', function() {
    const query = this.value;
    
    if (query.length < 2) {
        suggestions.innerHTML = '';
        return;
    }
    
    fetch(`https://api.example.com/suggest?q=${encodeURIComponent(query)}`)
        .then(response => response.json())
        .then(data => {
            suggestions.innerHTML = data.map(item => 
                `
${item}
` ).join(''); }); });

模拟搜索建议