如何封装一个Ajax函数
目录

如何封装ajax函数

一个ajax函数:

// 一个ajax函数
var xhr = null;
if(window.xmlhttprequest){
   xhr = new xmlhttprequest;
}else{
   xhr = new activexobject("microsoft.xmlhttp");
}
xhr.open("get","https://jsonplaceholder.typicode.com/users");
xhr.send(null);
xhr.onreadystatechange = function(){
   if(this.readystate === 4){
        console.log(xhr.responsetext)
    }
}

封装自己的 ajax 函数

参数1:{string} 请求方法--method
参数2:{string} 请求地址--url
参数3:{object} 请求参数--params
参数4:{function} 请求完成后,执行的回调函数--done

 function ajax(method,url,params,done){
//  统一将method方法中的字母转成大写,后面判断get方法时 就简单点
  method = method.touppercase(); 
  //ie6的兼容
  var xhr = window.xmlhttprequest
   ? new xmlhttprequest()
   : new activexobject("microsoft.xmlhttp");

  //创建打开一个连接 open
             
  //将对象格式的参数转为urlencoded模式
  //新建一个数组,使用for循环,将对象格式的参数,
  //以(id = 1)的形式,每一个键值对用 & 符号连接
 var pairs = [];
 for(var k in params){
     pairs.push(k + "=" + params[k]);
  }
  var str = pairs.join("&");       
  //判断是否是get方法 , get方法的话,需要更改url的值
 if(method == "get"){
       url += "?" + str;
  }
             
//创建打开一个连接
 xhr.open(method,url);

var data = null;
if(method == "post"){
    //post方法 还需要设置请求头、请求体
    xhr.setrequestheader("content-type",
    "application/x-www-form-urlencoded");
    data = str;
                 
}
xhr.send(data);

 //执行回调函数
xhr.onreadystatechange = function(){
   if(this.readystate == 4) {
       done(json.parse(this.responsetext));
   }return;
   // 执行外部传进来的回调函数即可
   // 需要用到响应体
   }
}  

//调用函数
//get方法
//  ajax("get","http://localhost:3000/users",
//     {"id":1},
//     function(data){
//         console.log(data);
//  });

//post方法     
ajax("post", "http://localhost:3000/users",
 { "name": "lucky","class":2,"age":20 },
 function (data) {
     console.log(data);
});

以上就是如何封装一个ajax函数的详细内容,更多关于封装ajax函数的资料请关注硕编程其它相关文章!

相关文章