使用 原生 XMLHttpRequest简单实现两个请求方式 GET 和POST
interface IOptions{
url:string;
type?:"GET"|"POST";
data:any;
timeout?:number;
}
// {}=>url 拼接得参数
function formatUrl(object:any){
let dataArr = []
for(let key in object){
dataArr.push(`${key}=${encodeURIComponent(object[key])}`)
}
return dataArr.join('&')
}
const ajax=(
options:IOptions = {
type:"GET",
data:{},
timeout:3000,
url:'',
})=>{
return new Promise((resolve,reject)=>{
if(!options.url) return
const queryString =formatUrl(options.data)
const stateChange = ()=>{
xhr.onreadystatechange=()=>{
if(xhr.readyState ===4){
clearTimeout(timer)
if((xhr.status>=200 && xhr.status<=300)|| xhr.status === 304){
resolve(xhr.responseText)
}else{
reject(xhr.status)
}
}
}
}
let timer;
let xhr;
const gload = window ?window:global
if((global as any).XMLHttpRequest){
xhr = new XMLHttpRequest()
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
switch (options.type.toUpperCase()) {
case 'GET':
xhr.open('GET',`${options.url}?${queryString}`)
stateChange()
break;
case 'POST':
xhr.open('POST',options.url)
xhr.setRequestHeader("ContentType",'application/x-www-form-urlencoded')
stateChange()
xhr.send(options.data)
break;
default:
break;
}
if(options.timeout){
timer = setTimeout(()=>{
xhr.abort()
reject('timeout')
},options.timeout)
}
})
}
ajax({type:'GET',url:'https://www.baidu.com',data:{wd:'typescript'}}).then(res=>{
console.log('twf',res)
})```