AJAX学习指南
向服务器发送请求 – 编程小白也能懂
什么是AJAX?
AJAX 全称是 “Asynchronous JavaScript and XML”,翻译过来就是”异步的 JavaScript 和 XML”。
🙋 想象你在餐厅点餐:
传统方式 – 每次点菜都要把菜单交给服务员,等他去厨房,再回来告诉你结果。
AJAX方式 – 你只需要告诉服务员想点什么,他立即用对讲机通知厨房,你继续用餐,菜好了服务员直接送来。
简单说,AJAX 允许网页:
- 在不重新加载整个页面的情况下
- 从服务器获取新数据
- 更新网页的某部分内容
这就是为什么你用 Google 搜索时,输入关键词下面就会实时出现相关建议。
为什么需要AJAX?
在AJAX出现之前,网页每次需要更新内容时都要完全刷新整个页面。
这样做的缺点:
- 用户体验差(页面闪烁)
- 浪费带宽(重复加载相同内容)
- 响应速度慢
AJAX解决了这些问题:
- 🔄 只更新需要变化的页面部分
- ⚡️ 更快地响应用户操作
- 📦 减少数据传输量
- 💫 创建更流畅的用户体验
几乎所有现代网站都使用AJAX:社交媒体动态加载、购物车更新、表单验证等。
AJAX工作原理
AJAX的核心是浏览器内置的 XMLHttpRequest 对象(XHR)。
工作流程如下:
- 用户触发事件(如点击按钮)
- JavaScript 创建 XHR 对象
- XHR 对象向服务器发送请求
- 服务器处理请求
- 服务器返回响应给浏览器
- JavaScript 处理响应并更新页面
// 1. 创建XHR对象
let xhr = new XMLHttpRequest();
// 2. 配置请求(方法、URL、异步)
xhr.open(‘GET’, ‘https://api.example.com/data’, true);
// 3. 发送请求
xhr.send();
// 4. 当请求状态变化时处理响应
xhr.onload = function() {
if (xhr.status == 200) {
// 请求成功,处理数据
console.log(xhr.responseText);
}
};
let xhr = new XMLHttpRequest();
// 2. 配置请求(方法、URL、异步)
xhr.open(‘GET’, ‘https://api.example.com/data’, true);
// 3. 发送请求
xhr.send();
// 4. 当请求状态变化时处理响应
xhr.onload = function() {
if (xhr.status == 200) {
// 请求成功,处理数据
console.log(xhr.responseText);
}
};
XMLHttpRequest vs Fetch API
XMLHttpRequest (XHR):
- 较老的AJAX技术
- 所有浏览器都支持
- API设计较复杂
Fetch API:
- 现代浏览器内置的新API
- 使用Promise,更简洁
- 语法更现代化
- 不支持IE浏览器
Fetch API基本用法:
// 发起GET请求
fetch(‘https://api.example.com/data’)
.then(response => response.json()) // 解析JSON响应
.then(data => {
console.log(data); // 处理数据
})
.catch(error => {
console.error(‘请求失败:’, error);
});
fetch(‘https://api.example.com/data’)
.then(response => response.json()) // 解析JSON响应
.then(data => {
console.log(data); // 处理数据
})
.catch(error => {
console.error(‘请求失败:’, error);
});
推荐在新项目中使用Fetch API,语法更简洁明了。
发送GET请求
GET请求用于获取数据,是最常用的请求类型。
特点:
- 数据通过URL参数传递
- 可以被浏览器缓存
- 有长度限制
- 不应该用于敏感数据
使用Fetch发送GET请求:
// 带查询参数的GET请求
fetch(‘https://api.example.com/users?limit=10&page=2’)
.then(response => {
if (!response.ok) {
throw new Error(‘网络响应异常’);
}
return response.json();
})
.then(data => {
console.log(‘获取的用户数据:’, data);
})
.catch(error => {
console.error(‘请求出错:’, error);
});
fetch(‘https://api.example.com/users?limit=10&page=2’)
.then(response => {
if (!response.ok) {
throw new Error(‘网络响应异常’);
}
return response.json();
})
.then(data => {
console.log(‘获取的用户数据:’, data);
})
.catch(error => {
console.error(‘请求出错:’, error);
});
发送POST请求
POST请求用于提交数据,如表单提交。
特点:
- 数据在请求体中发送
- 不会被缓存
- 没有长度限制
- 适合敏感数据
使用Fetch发送POST请求:
let userData = {
name: ‘张三’,
email: ‘zhangsan@example.com’
};
fetch(‘https://api.example.com/users’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’
},
body: JSON.stringify(userData) // 将对象转为JSON字符串
})
.then(response => response.json())
.then(data => {
console.log(‘创建的用户:’, data);
})
.catch(error => {
console.error(‘创建用户失败:’, error);
});
name: ‘张三’,
email: ‘zhangsan@example.com’
};
fetch(‘https://api.example.com/users’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’
},
body: JSON.stringify(userData) // 将对象转为JSON字符串
})
.then(response => response.json())
.then(data => {
console.log(‘创建的用户:’, data);
})
.catch(error => {
console.error(‘创建用户失败:’, error);
});
处理响应数据
服务器返回的数据有多种格式:
- JSON – 最常用的格式
- 文本 – 纯文本内容
- XML – 较少使用了
- Blob – 二进制数据(如图片)
处理JSON响应:
fetch(‘api/data.json’)
.then(response => response.json()) // 解析为JSON对象
.then(data => {
// 使用数据更新页面
document.getElementById(‘result’).innerHTML = data.message;
});
.then(response => response.json()) // 解析为JSON对象
.then(data => {
// 使用数据更新页面
document.getElementById(‘result’).innerHTML = data.message;
});
处理文本响应:
fetch(‘api/data.txt’)
.then(response => response.text()) // 获取文本
.then(text => {
console.log(text);
});
.then(response => response.text()) // 获取文本
.then(text => {
console.log(text);
});
错误处理
AJAX请求可能失败的原因:
- 网络连接问题
- 服务器错误(500状态码)
- 资源未找到(404状态码)
- 权限问题(401/403状态码)
使用Fetch的错误处理:
fetch(‘https://api.example.com/data’)
.then(response => {
// 检查响应状态
if (!response.ok) {
throw new Error(`HTTP错误! 状态码: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(‘成功获取数据’, data);
})
.catch(error => {
console.error(‘请求失败:’, error);
// 向用户显示错误信息
document.getElementById(‘error’).textContent = ‘加载数据失败,请重试’;
});
.then(response => {
// 检查响应状态
if (!response.ok) {
throw new Error(`HTTP错误! 状态码: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(‘成功获取数据’, data);
})
.catch(error => {
console.error(‘请求失败:’, error);
// 向用户显示错误信息
document.getElementById(‘error’).textContent = ‘加载数据失败,请重试’;
});
重要提示:fetch() 只有在网络错误时才抛出异常,对于HTTP错误状态码(404、500等),需要手动检查。
AJAX 请求演示
{/* 响应内容将在这里显示 */}
请点击上面的按钮发送请求…