如果用原生的js封装 ajax请求 在没有 jquery 或者 axios基础的 尝试下自己封装ajax函数
function ajax(url,type="get",callback,data){ // type 函数增强的特性 默认是get请求 callback是回调函数 对回来的数据进行处理
var xhr=new XMLHttpRequest(); //创建 ajax对象
if(type=="get"&&data!=undefined){ //如果 type等于get请求 同时 有请求参数的情况下 在地址后面拼接参数
url+="?"+data;
}
xhr.open(type,url,true) //函数的参数 顺序和这个open函数的参数顺序不太一样 别写乱了
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
var result=xhr.responseText; //获取从服务器端的回来的数据
callback(JSON.parse(result)); //由于从服务器端回来的数据是 json字符串 所以要解析成json对象
}
}
if(type=="post"&&data!=undefined){ //如果请求是post请求 同时有参数传进来 则设置请求头信息
xhr.setRequestHeader("Content-type","application/x-www--form-urlencoded");
xhr.send(data);
}else{
xhr.send();
}
}
方法2:用es6的promise方法来封装ajax方法 有基础可以看下
function proAjax({url,type="get",data}){
return new Promise(function(resolve,reject){
var xhr=new XMLHttpRequest();
console.log(xhr);
if(type=="get"&&data!=undefined){
url+="?"+data;
}
//ajax的请求是 xhr.open() 三个参数 是 第一个是请求类型 get or post 第二个参数是 请求地址 第三个参数 true同意 异步请求
xhr.open(type,url,true);
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
console.log(xhr.responseText);
var result=JSON.parse(xhr.responseText);
resolve(result);
}
}
if(type=="post"){
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
}else{
xhr.send();
}
})
}
下面是俩种方法的调用形式
1.原生: ajax("http://127.0.0.1:8080","get",function(result){
console.log(result);
},"uname=xiaoming")
2.promise调用方法:
proAjax({
url:"http://127.0.0.1",
type:"get",
data:"name=xiaoming"
}).then(result=>{
console.log(result);
})