跳转到内容

JavaScript Ajax基础

来自代码酷

JavaScript Ajax基础[编辑 | 编辑源代码]

Ajax(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容的技术。它通过JavaScript的XMLHttpRequest对象或现代的fetch API实现异步通信,广泛应用于动态网页开发。

介绍[编辑 | 编辑源代码]

Ajax允许网页在后台与服务器交换数据,从而实现局部更新,提升用户体验。其核心特点是:

  • 异步通信:无需刷新页面即可获取数据。
  • 轻量级传输:通常使用JSON或XML格式传输数据。
  • 事件驱动:通过回调函数或Promise处理响应。

XMLHttpRequest 基础[编辑 | 编辑源代码]

创建请求[编辑 | 编辑源代码]

使用XMLHttpRequest对象发起Ajax请求的基本步骤:

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

// 2. 配置请求(方法、URL、是否异步)
xhr.open('GET', 'https://api.example.com/data', true);

// 3. 设置响应类型(可选)
xhr.responseType = 'json';

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

// 5. 处理响应
xhr.onload = function() {
    if (xhr.status === 200) {
        console.log('成功获取数据:', xhr.response);
    } else {
        console.error('请求失败:', xhr.statusText);
    }
};

// 6. 错误处理
xhr.onerror = function() {
    console.error('网络错误');
};

请求方法[编辑 | 编辑源代码]

常见HTTP方法:

  • GET:获取数据
  • POST:提交数据
  • PUT/DELETE:更新/删除数据

发送数据[编辑 | 编辑源代码]

POST请求示例:

xhr.open('POST', 'https://api.example.com/submit', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ username: 'Alice', age: 25 }));

Fetch API[编辑 | 编辑源代码]

现代JavaScript推荐使用fetch API,基于Promise实现更简洁的异步操作:

fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) throw new Error('网络响应异常');
        return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('请求失败:', error));

异步/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);
    }
}

数据格式[编辑 | 编辑源代码]

常见的数据交换格式:

格式 特点 示例
轻量、易解析 | {"name":"Alice","age":25}
可扩展但冗长 | <user><name>Alice</name><age>25</age></user>

实际案例[编辑 | 编辑源代码]

实时搜索建议[编辑 | 编辑源代码]

以下示例展示如何实现搜索框的实时建议:

document.getElementById('search').addEventListener('input', async (e) => {
    const query = e.target.value;
    const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
    const suggestions = await response.json();
    displaySuggestions(suggestions);
});

用户登录验证[编辑 | 编辑源代码]

document.getElementById('login-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    const response = await fetch('/api/login', {
        method: 'POST',
        body: JSON.stringify(Object.fromEntries(formData)),
        headers: { 'Content-Type': 'application/json' }
    });

    if (response.ok) {
        window.location.href = '/dashboard';
    } else {
        alert('登录失败: ' + (await response.text()));
    }
});

跨域请求(CORS)[编辑 | 编辑源代码]

浏览器出于安全考虑会限制跨域请求。解决方法:

  • 服务器设置Access-Control-Allow-Origin
  • 使用JSONP(仅限GET请求)
  • 代理服务器转发请求

性能优化[编辑 | 编辑源代码]

  • 使用缓存(Cache-Control头)
  • 压缩数据(gzip)
  • 批量请求减少HTTP次数
  • 取消不必要的请求(AbortController

graph TD A[发起Ajax请求] --> B{请求成功?} B -->|是| C[处理数据] B -->|否| D[错误处理] C --> E[更新DOM] D --> F[显示错误信息]

数学表示[编辑 | 编辑源代码]

Ajax请求的延迟可表示为: Ttotal=Trequest+Tprocess+Tresponse 其中:

  • Trequest:请求发送时间
  • Tprocess:服务器处理时间
  • Tresponse:响应返回时间

参见[编辑 | 编辑源代码]