新手入门哈,封装ajax请求

342 篇文章 9 订阅
5 篇文章 0 订阅

如果用原生的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);

   })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yunchong_zhao

帮到你了,请作者喝杯矿泉水可好

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值