尝试着写了一下 肯定有很多不足之处~欢迎大家指出!
function myaxios(options = {}){
let method = options.method;
let url = options.url;
let data = options.data;
if (method == 'get') {
this.get(url)
}
if (method == 'post') {
this.post(url, data)
}
}
myaxios.prototype.get = function(url, options = {}){
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
if (options[params]) {
url += '?'
for(let key in options[params]){
url += key + '=' + params[key] + '&'
}
}
xhr.open('get', url, true);
xhr.onReadyStateChange = function(){
if (xhr.readyState == 4) {
if (200 <= xhr.status < 300 || xhr.status == 304) {
return resolve(xhr.responseText)
} else {
return reject(xhr.responseText)
}
}
}
xhr.send(null)
})
}
myaxios.prototype.post = function(url, data = {}){
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.onReadyStateChange = function(){
if (xhr.readyState == 4) {
if (200 <= xhr.status < 300 || xhr.status == 304) {
return resolve(xhr.responseText)
} else {
return reject(xhr.responseText)
}
}
}
xhr.send(data)
})
}