class myAjax{
constructor(newObj) {
this.obj = newObj;
}
ajax() {
//1.创建对象 通过兼容模式
let xhr;
if (window.ActiveXObject) {
//ie
xhr = new ActiveXObject("Microsoft.XMLHttp");
} else {
//非ie
xhr = new XMLHttpRequest();
}
this.obj.type = this.obj.type.toLowerCase();
if (this.obj.type == "get") {
let urlParam = this.obj.url;
urlParam += "?" + this.obj.data;
xhr.open(this.obj.type,urlParam, this.obj.isAsyn);
xhr.send();
} else if (this.obj.type == "post") {
xhr.open(this.obj.type, this.obj.url, this.obj.isAsyn);
//这句话必须抄 post的请求头
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(this.obj.data);
}
let that = this;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
that.obj.callBack(xhr.responseText);
}
}
}
}
测试
<script src="js/ajax插件.js"></script>
<script>
function fun(str){
console.log(str);
}
new myAjax({
"isAsyn":true,
"type":"get",
"url":"test.php",
"data":"name=laowang",
"callBack":fun
}).ajax();
</script>