ajax提交方式函数封装
ajax提交方式函数封装
export{
ajax
}
function ajax(){
new Ajax(...arguments)
}
class Ajax{
constructor({method,url,data}){
this.method = method;
this.url = url;
this.data = data;
this.init();
this.type()
}
init(){
var xhr= null;
try{
xhr = new XMLHttpRequest;
}catch{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
type(){
var xhr = this.init();
var querystring=""
if(this.data){
querystring = this.queryString(this.data);
}
if(this.method =="get"){
xhr.open(this.method,this.url+"?"+ querystring,true);
xhr.send()
}else{
xhr.open(this.method,this.url,true);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(querystring)
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
console.log(xhr.responseText)
}
}
}
queryString(dataObj){
var str = "";
for(var attr in dataObj){
str +=`${attr}=${dataObj[attr]}&`
}
return str.substring(0,str.length-1);
}
}
请用今天的努力,让明天没有遗憾。