function ajax(url, method = 'GET', data = {}, headers = {}) {
return new Promise((resolve, reject) => {
// 初始化XMLHttpRequest对象
const xhr = new XMLHttpRequest();
// 设置请求方法、URL以及是否异步(默认是true)
xhr.open(method, url, true);
// 设置请求头
for (let key in headers) {
if (headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, headers[key]);
}
}
// 设置请求完成时的回调函数
xhr.onreadystatechange = function () {
// 请求完成并且响应成功(状态码为200-299)
if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 300) {
try {
// 尝试解析响应为JSON(如果响应头指定了Content-Type为application/json)
const response = xhr.responseType === 'json' ? xhr.response : JSON.parse(xhr.responseText);
resolve(response);
} catch (e) {
// 解析失败时,将原始响应文本作为结果返回
resolve(xhr.responseText);
}
} else if (xhr.readyState === 4) {
// 请求完成但响应失败(状态码不是200-299)
reject(new Error(`Request failed with status ${xhr.status}: ${xhr.statusText}`));
}
};
// 处理GET请求
if (method === 'GET') {
const queryString = Object.keys(data)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
.join('&');
url = `${url}?${queryString}`;
xhr.send();
} else {
// 处理POST、PUT等请求,设置请求头为application/json
headers['Content-Type'] = 'application/json';
xhr.setRequestHeader('Content-Type', headers['Content-Type']);
xhr.send(JSON.stringify(data));
}
});
}
// 使用示例
ajax('https://api.example.com/data', 'GET')
.then(response => {
console.log('成功:', response);
})
.catch(error => {
console.error('错误:', error);
});
// POST请求示例
const postData = { key: 'value' };
ajax('https://api.example.com/data', 'POST', postData, { 'Authorization': 'Bearer YOUR_TOKEN' })
.then(response => {
console.log('成功:', response);
})
.catch(error => {
console.error('错误:', error);
});
console