JavaScript 封装 ajax ?
大家会想,现在根本用不到,如果出现某种特殊情况呢。例如:因安全原因把网页所需文件放入客户端项目中,不允许引入外部文件及第三方库。那是不是就需要你手动撸呐
封装 ajax
ajax(method, url, params)
- method = 请求类型
- url = 请求地址
- params 请求参数
function ajax(method, url, params) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
method = method.toLowerCase();
// 处理 GET 请求的查询参数
if (method === 'get' && params) {
const queryString = Object.keys(params)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
.join('&');
url += '?' + queryString;
}
xhr.open(method, url, true);
// 设置请求头
if (method === 'post') {
xhr.setRequestHeader('Content-Type', 'application/json');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
try {
// 尝试解析 JSON 响应
const response = JSON.parse(xhr.responseText);
resolve(response);
} catch (e) {
// 如果解析失败,返回原始文本
resolve(xhr.responseText);
}
} else {
// 处理错误状态码
reject(new Error('Request failed with status: ' + xhr.status));
}
}
};
// 发送请求
if (method === 'post') {
xhr.send(JSON.stringify(params));
} else {
xhr.send();
}
});
}
使用示例
ajax('GET', 'https://api.xxxx.com/data', { key: 'value' })
.then(data => {
console.log('Data received:', data);
})
.catch(err => {
console.error('Error:', err);
});
ajax('POST', 'https://api.xxxx.com/data', { key: 'value' })
.then(data => {
console.log('Response received:', data);
})
.catch(err => {
console.error('Error:', err);
});