欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ajax原理篇

程序员文章站 2024-03-24 17:49:58
...
//五个参数 type:GET/POST, url:请求地址,data:请求的数据,success:成功的回调函数
        // failed:失败的回调函数
         function Ajax(type,url,data,success,failed){
            
             var xhr = null,
                 type = type.toUpperCase(),
                 random = Math.random();
                  //创建ajax对象封装
             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&age=18&
                 
                 data = str.replace(/&$/,'');
                 console.log(data);//name=zlz&sex=female&age=18
             }
             if(type == 'GET'){
                 if(data){
                     xhr.open(type,url + '?' + data,true);
                 }else{
                     xhr.open(type,url + '?t=' +random,true);
                 }
                 xhr.send();
             }else if(type == 'POST'){
                 xhr.open('POST',url,true);
                 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);
         })