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

  //五个参数 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);
         })

 

你可能感兴趣的:(javascript)