用promise和ajax封装axios

尝试着写了一下 肯定有很多不足之处~欢迎大家指出!

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)
	})
}

猜你喜欢

转载自blog.csdn.net/Sallywa/article/details/89416198