javascript实现Ajax
封面图
•
2026-01-17
•
JavaScript
229
0
0
0
在 JavaScript 中实现 **Ajax(Asynchronous JavaScript and XML)**,主要是通过 `XMLHttpRequest` 对象或现代的 `fetch()` API 来与服务器进行异步通信。下面分别介绍这两种方法。 --- ## ✅ 1. 使用 `XMLHttpRequest` 实现 Ajax ```javascript // 创建 XMLHttpRequest 对象 var xhr = new XMLHttpRequest(); // 设置请求方法和 URL xhr.open('GET', 'https://api.example.com/data', true); // 设置请求头(可选) xhr.setRequestHeader('Content-Type', 'application/json'); // 设置响应处理 xhr.onreadystatechange = function () { if (xhr.readyState === 4) { // 请求完成 if (xhr.status === 200) { // 响应成功 console.log('响应数据:', xhr.responseText); } else { console.error('请求失败:', xhr.status); } } }; // 发送请求 xhr.send(); ``` ### 示例:GET 请求 ```javascript var xhr = new XMLHttpRequest(); xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true); xhr.onload = function () { if (xhr.status >= 200 && xhr.status < 300) { var data = JSON.parse(xhr.responseText); console.log(data); } else { console.error('请求失败:', xhr.statusText); } }; xhr.send(); ``` --- ## ✅ 2. 使用 `fetch()` API 实现 Ajax(更现代的方式) ```javascript fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('网络响应错误: ' + response.statusText); } return response.json(); // 解析 JSON 数据 }) .then(data => { console.log('获取到的数据:', data); }) .catch(error => { console.error('请求出错:', error); }); ``` ### 示例:POST 请求 ```javascript fetch('https://api.example.com/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: '张三', age: 25 }) }) .then(response => response.json()) .then(data => console.log('提交成功:', data)) .catch(error => console.error('提交失败:', error)); ``` --- ## ✅ 3. 使用 `async/await` 简化 fetch ```javascript async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('网络响应错误: ' + response.statusText); } const data = await response.json(); console.log('数据:', data); } catch (error) { console.error('请求失败:', error); } } fetchData(); ``` --- ## 📌 总结 | 方法 | 特点 | |------|------| | `XMLHttpRequest` | 传统方式,兼容性好 | | `fetch()` | 更简洁、现代,支持 Promise | | `async/await` | 使异步代码更易读 | --- 如果你有具体的接口或需求(比如 GET / POST / PUT / DELETE),我可以帮你写出对应的完整示例。欢迎继续提问!
上一篇:
JavaScript中typeof运算符介绍
下一篇:
JavaScript Cookies介绍
标题录入,一次不能超过6条
留言
评论