使用js封装一个ajax方法
当封装一个 AJAX 方法时,你可以使用原生的 JavaScript XMLHttpRequest
对象或者使用更现代的 fetch
API。下面,我将为你提供一个使用 XMLHttpRequest
对象的简单 AJAX 封装示例,以及一个使用 fetch
API 的示例。
使用 XMLHttpRequest
封装 AJAX 方法
function ajax(options) {
// 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();
// 设置请求方法和 URL
xhr.open(options.method, options.url, true);
// 如果提供了请求头,则设置它们
if (options.headers) {
for (const key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
}
// 处理响应
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
// 请求成功,调用 success 回调
if (typeof options.success === 'function') {
options.success(xhr.responseText);
}
} else {
// 请求失败,调用 error 回调
if (typeof options.error === 'function') {
options.error(xhr.statusText);
}
}
};
// 发送请求,如果提供了数据则发送数据
if (options.data) {
xhr.send(options.data);
} else {
xhr.send();
}
}
// 使用示例:
ajax({
method: 'GET',
url: 'https://api.example.com/data',
headers: {
'Content-Type': 'application/json'
},
success: function(response) {
console.log('请求成功:', response);
},
error: function(error) {
console.log('请求失败:', error);
}
});
使用 fetch
API 封装 AJAX 方法
如果你正在开发一个现代的前端应用,并且目标浏览器支持 fetch
API,那么使用 fetch
会更加简洁和强大。
async function ajax(options) {
try {
// 发送 fetch 请求
const response = await fetch(options.url, {
method: options.method,
headers: options.headers,
body: options.data ? JSON.stringify(options.data) : null
});
// 检查响应状态
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 解析响应并返回数据
const data = await response.json();
if (typeof options.success === 'function') {
options.success(data);
}
} catch (error) {
// 处理请求错误
if (typeof options.error === 'function') {
options.error(error.message);
}
}
}
// 使用示例:
ajax({
method: 'GET',
url: 'https://api.example.com/data',
headers: {
'Content-Type': 'application/json'
},
success: function(data) {
console.log('请求成功:', data);
},
error: function(error) {
console.log('请求失败:', error);
}
});
请注意,在使用 fetch
时,默认情况下它不会抛出错误来响应 HTTP 错误状态(如 404 或 500)。因此,在上面的示例中,我们显式地检查了 response.ok
属性,并在必要时抛出了一个错误。