封装Ajax 命名Ajax.js
function ajax(options) {
let defaults={
type:'get',
url:'',
data:{},
header:{'Content-type':'application/json'},
success:function(){},
error:function(){}
}
Object.assign(defaults,options)
let xhr = new XMLHttpRequest();
let dataArr=[];
for (let key in defaults.data) {
dataArr.push(`${key}=${defaults.data[key]}`)
}
let params=dataArr.join('&');
if (defaults.type=='get') {
defaults.url=defaults.url+'?'+params
}
xhr.open(defaults.type,defaults.url);
if (defaults.type=='post') {
xhr.setRequestHeader("Content-Type",defaults.header['content-type'])
xhr.send(JSON.stringify(defaults.data));
}else{
xhr.send();
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let result =xhr.responseText;
let header=xhr.getResponseHeader('Content-Type')
if (header.includes('application/json')) {
result=JSON.parse(result)
}
options.success && options.success(result)
}else if(xhr.readyState==4 && xhr.status!=200){
options.error && options.error(xhr.status,xhr)
}
}
}
使用封装Ajax.js
<script src="js/ajax.js"></script>
ajax({
type:'',
url:'',
data:{},
success:function(data){
console.log(data)
},
error:function(){
}
})