使用原生js封装ajax,post、get请求

本文介绍了一个简易的AJAX函数实现方法,包括GET和POST请求方式,详细解释了如何设置请求头、发送数据及处理响应。通过具体示例展示了如何调用此函数进行数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  //五个参数 type:GET/POST, url:请求地址,data:请求的数据,success:成功的回调函数
        // failed:失败的回调函数
         function Ajax(type,url,data,success,failed){
             //创建ajax对象
             var xhr = null,
                 random = Math.random(),
                 type = type.toUpperCase();
             if(window.XMLHttpRequest){
                 xhr = new XMLHttpRequest();
             }else{
                 xhr = new ActiveXObject('Microsoft.XMLHTTP');
             }

             if(typeof data == 'object'){
                 var str = '';
                 for(var key in data){

                     str += key+'='+data[key]+'&';
                 }
                 console.log(str);//name=zlz&sex=female&
                 
                 data = str.replace(/&$/,'');
                 console.log(data);//name=zlz&sex=female
             }
             if(type == 'GET'){
                 if(data){
                     xhr.open('GET',url + '?' + data,true);
                 }else{
                     xhr.open('GET',url + '?t=' +random,true);
                 }
                 xhr.send();
             }else if(type == 'POST'){
                 xhr.open('POST',url,true);
                 //如果需要像html表单那样 post数据,请使用 setRequestHeader() 来添加http头
                 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                 xhr.send(data);
             }

             //处理返回数据
             xhr.onreadystatechange = function (){
                 if(xhr.readyState == 4){
                     if(xhr.status == 200){
                         success(xhr.responseText);
                     }else{
                         if(failed){
                             failed(xhr.status);
                         }
                     }
                 }
             }
         }   
        //测试调用
         var sendData = {name:'zlz',sex:'female',age:18}
         Ajax('post','test1.html',sendData,function(data){
             
             console.log(data);
         },function(error){
             console.log('error'+error);
         })

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值