<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 封装一个ajax的函数
const myAjax=obj=>{
//默认对象村ajax请求的默认值
let settings={
type:'get',
isAsync:true,
data:{}
}
// 接受到的对象,里面是配置参数
console.log(obj)
//讲settings作为源对, 将obj和settings '属性合并'
Object.assign(settings,obj)
// 查看settings
console.log(settings)
// 将settings里的值解构出来
let {type,isAsync,data,url,success,error} = settings
console.log(data)
//讲data 变成urlencoded格式 ? did=1&start=0&end=5
console.log(Object.keys(data))
// 对data的属性名数组进行遍历
//data格式化后的字符串
let str=''
//
Object.keys(data).forEach(item=>{return str +=item+'='+data[item]+'&'})
// 截取掉最后一个&符
str=str.slice(0,-1)
console.log(str)
let xhr=new XMLHttpRequest()
if(type==='get'){
xhr.open(type,url+'?'+str,isAsync)
}
xhr.open(type,url,isAsync)
xhr.onreadystatechange=function(){
if(this,readyState==4){
if(this,status==200){
success(this.responseText)
}else{
error()
}
}
}
if(type==='post'){
xhr.setRequestHeader('content-type','application/x-www-urlencoded')
xhr.send(str);
}else{
xh.send()
}
}
myAjax({
url:"xxx",
type:"post",
isAsync:true,
data:{
did:1,
statr:0,
end:5
},
success:function(res){
console.log(res)
},
Error:function(){
console.log('请求失败')
}
})
/*
object.assign()
从对象中结构出值
object.keys()
箭头函数
*/
</script>
</body>
</html>