使用promise封装原生Ajax

function sendAjax(methd,url,data){
	return new Promise(resolve,reject) => {
	//1.创建xhr对象
	let xhr = new XMLHttpRequest()
	//2.绑定监听
	xhr.onreadystatechange = function(){
	if(xhr.readyState !== 4){
		return
	}
	if(xhr.readystate === 4 && (xhr.status >= 200 && xhr.status <= 299)){
		const responseObj = {
			data:xhr.response,
			status:xhr.status,
			statusText:xhr.statusText
		}
		resolve(responseObj)
	}else{
	reject(new Error('请求出错了'));
	}
	//3.设置请求的方式,地址,传递的参数
	let dataKeys = object.keys(data)
	//4.将传递过来的数据对象,加工成urlencode对象的编码
	let str = datakeys.reducer(function(pre,now){
	return pre += `${now}=${data[now]}&`
	},'')
	//5.发送请求
	if(method.toLowerCase() === 'get'){
		url += `?${str}`
		xhr.open(method,url)
		xhr.send()
	}else if (method.toLowerCase()==='post'){
		xhr.open(method,url)
		xhr.setRequestheader('content-type','application/x-www-form-urlencoded')
		xhr.send(str)
	}
	})
	}
}

发送ajax(测试)
sendAjax(‘get’,‘http://localhost:3000/test_get’,{m:1,n:2})
.then(data => console.log(data))
.catch(err => console.log(err))
第二次发送,需要携带第一次的数据
async () => {
let {data} = await sendAjax(‘GET’,‘http://localhost:3000/test_get,{m:1,n:2}’)
let {data2} = await sendAjax(‘GET’,‘http://localhost:3000/test_get’,{data})
}

发布了29 篇原创文章 · 获赞 0 · 访问量 189

猜你喜欢

转载自blog.csdn.net/qq_41523392/article/details/103812345
今日推荐