练手封装下ajax,不是很好,正经应该是promise封装,再看看
class HttpClient{
constructor(){
this.xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP"); // 后面兼容IE5,6
}
get(url,params){
const xhr = this.xhr
if(typeof url === 'string'){
xhr.open('get',params?`${url}?${qs.stringify(params)}`:url,true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
return JSON.parse(xhr.responseText);
}
}
}
}else{
throw new TypeError(' get url error')
}
}
post(url,params,header){
const xhr = this.xhr
if(typeof url !== 'string'){
throw new TypeError('post url error');
return
}
xhr.open('post',url,true);
//header参数没有接,有需求得改一下
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params?qs.stringify(params):'');
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
return JSON.parse(xhr.responseText);
}
}
}
}
}
const httpClient = new HttpClient();
console.log(httpClient,'httpClient');