网络请求
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://xxxx.com/index.php/api', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText)
// 处理响应数据
console.log(response);
}
};
xhr.send();
另一种方式
fetch('http://xxxxxxxxx.com/index.php/api')
.then(response => response.json())
.then(data => {
// 处理响应数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error(error);
});
封装
// 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').then(result => {
// 处理响应数据
// console.log(result.data.state);
}).catch(error => {
// 处理错误
console.error(error);
});