var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://域名.com', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText)
// 处理响应数据
console.log(response);
}
};
xhr.send();
封装
// apiUtils.js
const url = 'http://域名.com';
export function fetchData(api) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url + api, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
// 处理响应数据
resolve(response);
} else {
// 处理错误
reject(new Error('Request failed. Status: ' + xhr.status));
}
}
};
xhr.send();
});
}
使用
fetchData('api' + res.code).then(result => {
// 处理响应数据
// console.log(result.data.state);
}).catch(error => {
// 处理错误
console.error(error);
});