AJAX函數(shù)的封裝

如何封裝Ajax函數(shù)

一個(gè)Ajax函數(shù):

// 一個(gè)Ajax函數(shù)
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 函數(shù)

參數(shù)1:{string} 請求方法--method
參數(shù)2:{string} 請求地址--url
參數(shù)3:{object} 請求參數(shù)--params
參數(shù)4:{function} 請求完成后,執(zhí)行的回調(diào)函數(shù)--done

 function ajax(method,url,params,done){
//  統(tǒng)一將method方法中的字母轉(zhuǎn)成大寫,后面判斷GET方法時(shí) 就簡單點(diǎn)
  method = method.toUpperCase(); 
  //IE6的兼容
  var xhr = window.XMLHttpRequest
   ? new XMLHttpRequest()
   : new ActiveXObject("Microsoft.XMLHTTP");

  //創(chuàng)建打開一個(gè)連接 open
             
  //將對象格式的參數(shù)轉(zhuǎn)為urlencoded模式
  //新建一個(gè)數(shù)組,使用for循環(huán),將對象格式的參數(shù),
  //以(id = 1)的形式,每一個(gè)鍵值對用 & 符號連接
 var pairs = [];
 for(var k in params){
     pairs.push(k + "=" + params[k]);
  }
  var str = pairs.join("&");       
  //判斷是否是get方法 , get方法的話,需要更改url的值
 if(method == "GET"){
       url += "?" + str;
  }
             
//創(chuàng)建打開一個(gè)連接
 xhr.open(method,url);

var data = null;
if(method == "POST"){
    //post方法 還需要設(shè)置請求頭、請求體
    xhr.setRequestHeader("Content-Type",
    "application/x-www-form-urlencoded");
    data = str;
                 
}
xhr.send(data);

 //執(zhí)行回調(diào)函數(shù)
xhr.onreadystatechange = function(){
   if(this.readyState == 4) {
       done(JSON.parse(this.responseText));
   }return;
   // 執(zhí)行外部傳進(jìn)來的回調(diào)函數(shù)即可
   // 需要用到響應(yīng)體
   }
}  

//調(diào)用函數(shù)
//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);
});
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容