跳转到内容

HTML AJAX请求

来自代码酷

HTML AJAX请求[编辑 | 编辑源代码]

AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下,通过JavaScript与服务器交换数据并更新部分网页内容的技术。它允许开发者创建快速、动态的网页应用,提升用户体验。本章节将详细介绍如何在HTML中通过JavaScript实现AJAX请求。

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

AJAX的核心是通过XMLHttpRequest对象(现代也可使用Fetch API)与服务器进行异步通信。它能够:

  • 在后台发送HTTP请求
  • 接收服务器返回的数据(JSON、XML、HTML或纯文本)
  • 动态更新页面内容而无需刷新

AJAX的工作流程通常如下:

sequenceDiagram participant 用户 participant 浏览器 participant 服务器 用户->>浏览器: 触发事件(如点击按钮) 浏览器->>服务器: 发送AJAX请求 服务器-->>浏览器: 返回响应数据 浏览器->>用户: 动态更新页面内容

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

以下是使用传统XMLHttpRequest对象的基本示例:

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

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

// 3. 设置回调函数处理响应
xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
        // 请求成功
        console.log('响应数据:', xhr.responseText);
        document.getElementById('result').innerHTML = xhr.responseText;
    } else {
        // 请求失败
        console.error('请求失败:', xhr.statusText);
    }
};

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

代码解析[编辑 | 编辑源代码]

1. new XMLHttpRequest() - 创建XHR对象 2. open() - 初始化请求参数 3. onload - 请求完成时的回调 4. send() - 发送请求

Fetch API(现代方法)[编辑 | 编辑源代码]

现代JavaScript推荐使用更简洁的Fetch API:

fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应异常');
        }
        return response.json(); // 解析JSON数据
    })
    .then(data => {
        console.log('获取的数据:', data);
        document.getElementById('result').innerHTML = JSON.stringify(data);
    })
    .catch(error => {
        console.error('请求错误:', error);
    });

优势[编辑 | 编辑源代码]

  • 基于Promise,更易处理异步操作
  • 更简洁的语法
  • 默认支持JSON解析

请求类型[编辑 | 编辑源代码]

GET 请求[编辑 | 编辑源代码]

用于获取数据:

fetch('/api/users?id=123')
    .then(response => response.json())
    .then(data => console.log(data));

POST 请求[编辑 | 编辑源代码]

用于提交数据:

fetch('/api/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({name: 'John', age: 30})
})
.then(response => response.json())
.then(data => console.log(data));

处理不同响应类型[编辑 | 编辑源代码]

|响应类型 |处理方法 |示例 |-

| JSON | response.json() |

fetch(...).then(res => res.json())

|-

| 文本 | response.text() |

fetch(...).then(res => res.text())

|-

| Blob | response.blob() |

fetch(...).then(res => res.blob())

错误处理[编辑 | 编辑源代码]

AJAX请求可能因多种原因失败,需要妥善处理:

fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
        return response.json();
    })
    .catch(error => {
        console.error('请求失败:', error);
        // 显示用户友好的错误信息
        document.getElementById('error').textContent = '无法加载数据,请稍后重试';
    });

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

案例1:实时搜索[编辑 | 编辑源代码]

用户在搜索框输入时,实时从服务器获取搜索结果:

<input type="text" id="search" placeholder="搜索...">
<div id="results"></div>

<script>
document.getElementById('search').addEventListener('input', function(e) {
    const query = e.target.value;
    if (query.length < 2) return;
    
    fetch(`/search?q=${encodeURIComponent(query)}`)
        .then(res => res.json())
        .then(data => {
            const results = document.getElementById('results');
            results.innerHTML = data.map(item => 
                `<div class="result-item">${item.title}</div>`
            ).join('');
        });
});
</script>

案例2:无限滚动[编辑 | 编辑源代码]

当用户滚动到页面底部时,自动加载更多内容:

window.addEventListener('scroll', function() {
    if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
        loadMoreContent();
    }
});

let currentPage = 1;
function loadMoreContent() {
    fetch(`/posts?page=${currentPage}`)
        .then(res => res.json())
        .then(posts => {
            posts.forEach(post => {
                document.getElementById('content').appendChild(
                    createPostElement(post)
                );
            });
            currentPage++;
        });
}

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

当请求不同源的资源时,需要了解同源策略CORS(跨源资源共享):

graph LR A[浏览器] -->|请求| B[服务器] B -->|响应头 Access-Control-Allow-Origin| A

处理跨域请求:

fetch('https://other-domain.com/api', {
    mode: 'cors', // 默认值
    headers: {
        'Content-Type': 'application/json'
    }
})
.then(response => response.json())
.catch(error => console.error('CORS错误:', error));

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

1. 节流与防抖 - 控制请求频率 2. 缓存响应 - 避免重复请求相同数据 3. 取消请求 - 使用AbortController

// 取消请求示例
const controller = new AbortController();
const signal = controller.signal;

fetch('/api/data', { signal })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => {
        if (err.name === 'AbortError') {
            console.log('请求被取消');
        }
    });

// 需要时取消请求
controller.abort();

总结[编辑 | 编辑源代码]

AJAX是现代Web开发的核心技术之一,通过本章学习,你应该了解:

  • XMLHttpRequest和Fetch API的基本用法
  • 如何处理不同类型的请求和响应
  • 错误处理和性能优化技巧
  • 实际应用场景的实现方法

随着Web技术的发展,AJAX仍然是创建动态、响应式网页应用的重要工具。