作者:
作者:xl
/**
* 1. 创建 XmlHttpRequest 对象
* 2. 初始化
* 3. 发送消息
* 4. 接收消息
*/
function ajax(options) {
// 创建一个 xhr 实例
const xhr = new XMLHttpRequest();
// 初始化请求
xhr.open('GET', options.url);
// 接收请求
// 当 readyState 属性发生变化时
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
const status = xhr.status;
if (status === 200) {
options.success?.(xhr.response);
} else {
options.fail?.(xhr.response);
}
}
}
// 接收错误
xhr.onerror = function(e) {
options.fail?.(e);
}
// 指定响应类型
xhr.responseType = 'json';
// 设置请求头
// xhr.setRequestHeader();
// 发起请求
xhr.send();
}
ajax({
url: 'https://segmentfault.com/gateway/article/1190000017176090/related',
success(data) {
console.log('data', data);
},
fail(data) {
console.log('err', data);
},
})
作者:奥兰度
function ajax(url, method) {
let xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.send()
}
作者:gochri
const getJSON = function (url = 'test.html',method = 'GET',[...settings]) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, false);
// settings
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
if (xhr.status === 200 || xhr.status === 304) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.responseText));
}
};
xhr.send();
});
};
作者:
作者: