创建js文件
function Ajax(option){
this.options = option
this.newpop()
}
Ajax.prototype.createAjax = function(){
let xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
Ajax.prototype.newpop = function(){
that = this
this.ajax()
}
Ajax.prototype.getValStr = function(dataObj){
let arr= [];
for(var key in dataObj){
arr.push(key+"="+dataObj[key]);
}
var datas = arr.join("&");
return datas;
}
Ajax.prototype.ajax = function(){
var xhr = this.createAjax()
console.log(xhr);
var types = this.options.type.toLowerCase();
console.log(types);
var datas = this.getValStr(this.options.data)
console.log(datas);
if(types == 'post'){
xhr.open(this.options.type,this.options.url)
}
if(types == "get"){
this.options.url = this.options.url+ "?" + datas
}else if(types === "post"){
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
}else{
console.log("传输方式错误");
}
if(types === 'get'){
xhr.open(this.options.type,this.options.url)
}
xhr.send(types == "get"? null : datas)
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
let data = JSON.parse(xhr.responseText)
if(xhr.status==200){
that.options.success(data)
}else{
that.this.options.error(data)
}
}
}
}
html调用
<script src="./api.js"></script>
<script>
new Ajax({
type:"get",
url:"http://localhost:3000/getCartList",
data:{
username:"zhangye",
password:"123123"
},
success: function(res){
console.log(res);
},
error:function(res){
console.log(res);
}
})
</script>