封装原生js ajax函数
function ajax(type,url,data,callback){
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
if(typeof data == "object"){
var str = ""
for(var key in data){
str += `${key}=${data[key]}&`
}
data = str.slice(0,str.length - 1)
}
type = type.toUpperCase()
if(type == "GET"){
if(data){
xhr.open("GET",`${url}?${data}`,true)
}else{
xhr.open("GET",url,true)
}
xhr.send()
}else if(type == "POST"){
xhr.open('POST',url,true)
if(data){
xhr.send(data)
}else{
xhr.send()
}
}else{
return "error"
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
var res = xhr.responseText
callback?callback(
function(){
return res
}()):""
}
}
}
调用代码
ajax("get","./test.txt",null,function(response){
console.log("dosomething....")
var res = response
console.log(res)
});
输出结果
标签:function,type,学习,xhr,ajax,res,var,data
来源: https://www.cnblogs.com/gehaoyu/p/11869192.html