推荐答案
// www.javascriptcn.com code example
function ajax(options) {
const { url, method = 'GET', data = null, headers = {}, success, error } = options;
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
// 设置请求头
for (const key in headers) {
xhr.setRequestHeader(key, headers[key]);
}
// 处理响应
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
success && success(xhr.responseText);
} else {
error && error(xhr.statusText);
}
};
// 处理错误
xhr.onerror = function() {
error && error('Network Error');
};
// 发送请求
xhr.send(data);
}本题详细解读
1. 函数参数
options: 一个包含请求配置的对象,包含以下属性:
url: 请求的URL地址。
method: 请求方法,默认为 'GET'。
data: 请求体数据,默认为 null。
headers: 请求头对象,默认为空对象 {}。
success: 请求成功时的回调函数。
error: 请求失败时的回调函数。
2. 创建 XMLHttpRequest 对象
- 使用
new XMLHttpRequest() 创建一个新的 XMLHttpRequest 对象。
3. 打开请求
- 使用
xhr.open(method, url, true) 初始化请求。method 是请求方法,url 是请求地址,true 表示异步请求。
4. 设置请求头
- 遍历
headers 对象,使用 xhr.setRequestHeader(key, headers[key]) 设置请求头。
5. 处理响应
- 使用
xhr.onload 监听请求完成事件。如果状态码在 200 到 299 之间,表示请求成功,调用 success 回调函数并传入响应文本 xhr.responseText。否则,调用 error 回调函数并传入状态文本 xhr.statusText。
6. 处理错误
- 使用
xhr.onerror 监听请求错误事件。如果发生网络错误,调用 error 回调函数并传入 'Network Error'。
7. 发送请求
- 使用
xhr.send(data) 发送请求。data 是请求体数据,如果为 null 或 undefined,则不发送请求体。
8. 使用示例
// www.javascriptcn.com code example
ajax({
url: 'https://api.example.com/data',
method: 'POST',
data: JSON.stringify({ key: 'value' }),
headers: {
'Content-Type': 'application/json'
},
success: function(response) {
console.log('Success:', response);
},
error: function(err) {
console.error('Error:', err);
}
});