12.使用Promise封装Ajax
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
// 封装Ajax请求的Promise函数
function fetchData(url, options = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(options.method || 'GET', url);
// 设置请求头
if (options.headers) {
Object.keys(options.headers).forEach(key => {
xhr.setRequestHeader(key, options.headers[key]);
});
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
// 转换响应数据为JSON
let response;
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
response = xhr.responseText;
}
resolve(response);
} else {
reject(new Error(`Status code: ${xhr.status}`));
}
};
xhr.onerror = () => {
reject(new Error('Network error'));
};
// 发送请求
xhr.send(options.body);
});
}
// 使用封装后的Promise进行Ajax请求
fetchData('https://api.example.com/data', { method: 'GET' })
.then(data => console.log(data))
.catch(error => console.error(error));
这段代码定义了一个fetchData
函数,它接受一个URL和一个配置对象作为参数,并返回一个Promise。根据传入的HTTP方法和头部信息,它发起Ajax请求,并在请求成功或失败时调用resolve
或reject
。使用时,可以通过.then()
和.catch()
处理请求的成功或错误情况。
评论已关闭