Ajax 请求实现
使用原生 JavaScript 创建 Ajax 请求
问题
如何使用原生 JavaScript 创建 Ajax 请求?
解答
使用 XMLHttpRequest
function ajax(options) {
const { method = 'GET', url, data = null, headers = {} } = options;
return new Promise((resolve, reject) => {
// 1. 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();
// 2. 初始化请求
xhr.open(method, url, true);
// 3. 设置请求头
for (const key in headers) {
xhr.setRequestHeader(key, headers[key]);
}
// 4. 监听状态变化
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error(`Request failed with status ${xhr.status}`));
}
};
// 5. 处理网络错误
xhr.onerror = function () {
reject(new Error('Network error'));
};
// 6. 发送请求
xhr.send(data ? JSON.stringify(data) : null);
});
}
// 使用示例
ajax({
method: 'GET',
url: 'https://api.example.com/users'
}).then(data => {
console.log(data);
}).catch(err => {
console.error(err);
});
GET 请求带参数
function get(url, params = {}) {
// 拼接查询字符串
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
const fullUrl = queryString ? `${url}?${queryString}` : url;
return ajax({ method: 'GET', url: fullUrl });
}
// 使用
get('/api/users', { page: 1, limit: 10 });
POST 请求
function post(url, data) {
return ajax({
method: 'POST',
url,
data,
headers: {
'Content-Type': 'application/json'
}
});
}
// 使用
post('/api/users', { name: 'Tom', age: 18 });
readyState 状态值
| 值 | 状态 | 说明 |
|---|---|---|
| 0 | UNSENT | 未调用 open() |
| 1 | OPENED | 已调用 open() |
| 2 | HEADERS_RECEIVED | 已接收响应头 |
| 3 | LOADING | 正在接收响应体 |
| 4 | DONE | 请求完成 |
关键点
new XMLHttpRequest()创建请求对象open(method, url, async)初始化请求,第三个参数表示是否异步setRequestHeader()必须在open()之后、send()之前调用readyState === 4表示请求完成,需配合status判断是否成功- POST 请求需设置
Content-Type,数据通过send()发送
目录