精简版(仅核心功能):
javascript
function simpleAjax(url, method = 'GET', data = null) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = () => reject(new Error('网络错误'));
xhr.send(data);
});
}
完整版:
封装说明
- 基本功能:支持GET/POST等方法,自动处理JSON数据
- 错误处理:包含HTTP状态码、网络错误、超时等错误处理
- 响应解析:自动识别JSON响应并解析
- 头部支持:可自定义请求头
- 扩展性:可根据需要添加超时设置、进度监听等功能
javascript
function ajaxPromise(options) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(options.method || 'GET', options.url, true);
// 设置请求头(可自定义)
if (options.headers) {
for (let key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const response = xhr.responseText;
const contentType = xhr.getResponseHeader('Content-Type');
// 自动解析JSON响应
let data = response;
if (contentType && contentType.includes('application/json')) {
data = JSON.parse(response);
}
resolve({
data: data,
status: xhr.status,
xhr: xhr
});
} catch (error) {
reject(new Error(`解析响应失败: ${error.message}`));
}
} else {
reject(new Error(`请求失败: ${xhr.status} ${xhr.statusText}`));
}
}
};
xhr.onerror = function() {
reject(new Error('网络错误'));
};
xhr.ontimeout = function() {
reject(new Error('请求超时'));
};
// 发送请求
if (options.data) {
let body = options.data;
if (typeof body === 'object') {
body = JSON.stringify(body);
xhr.setRequestHeader('Content-Type', 'application/json');
}
xhr.send(body);
} else {
xhr.send();
}
});
}
// 使用示例
ajaxPromise({
url: 'https://api.example.com/data',
method: 'GET'
})
.then(response => {
console.log('请求成功:', response.data);
})
.catch(error => {
console.error('请求失败:', error.message);
});
// POST请求示例
ajaxPromise({
url: 'https://api.example.com/submit',
method: 'POST',
data: { name: '张三', age: 25 },
headers: {
'Authorization': 'Bearer token123'
}
})
.then(response => console.log('提交成功:', response.data))
.catch(error => console.error('提交失败:', error));