封装原则 把可能会变动的内容,都给弄参数,让用户传递进来
function aa({url,type=‘get’,async=true,data}){
处理兼容问题
var xhr=null
try{
xhr = new XMLHttpRequest()
}catch(e){
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
处理参数
if(data){
data = xxoo(data)
}
function xxoo(d){
var newData=''
for(var i in d){
newData +=i +"="+d[i]+"&"
//name='张三'&age=18&
}
return newData.substr(0,newData.length-1)
}
if(type == 'get' && data){
url += "?"+data
}
if(type =='get'){
//初始化
xhr.open(type,url,async)
//发送
xhr.send()
}else{
xhr.open(type,url,async)
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
xhr.send(data)
}
响应数据
xhr.onreadystatechange=function(){
if(xhr.readyStat==4 && xhr.status == 200){
xhr.response
}
}
}
aa({
url:'1.php',
data:{
name:'张三',
age:'18'
}
})
本文介绍了一种封装AJAX请求的方法,通过将可能变化的部分作为参数传递,提高代码复用性和维护性。支持GET和POST两种请求方式,并处理了数据转换及兼容性问题。
1637

被折叠的 条评论
为什么被折叠?



