class Ajax{
constructor(url, method, data, callback_suc, callback_err, callback_run){
this.RT = true;//默认为异步请求
this.url = url;
this.method = method || "POST";
this.data = data || "";
this.callback_suc = callback_suc || function () {};
this.callback_err = callback_err || function () {};
this.callback_run = callback_run || function () {};
if(!this.url){this.callback_err(); return;}
this.createRequest();
}
createRequest(){
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = (e)=>{this.run(e);}
xhr.open(this.method, this.url, this.RT);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(this.data);
}
run(e){
this.callback_run(e);
if(e.target.readyState !== 4 || e.target.status !== 200){return;}
this.callback_suc(e);
}
}
//调用:
new Ajax(
"./main.php", //url:请求地址
"POST", //method:请求方法
"data=3&sb=2",//data:传递数据
(e)=>{//callback_suc:请求完成 回调函数
document.write(e.target.responseText);//3
},
(e)=>{},//callback_err:请求错误 回调函数
(e)=>{}//callback_run:请求中 回调函数
)
|