// 一個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)
}
}
function ajax(method,url,params,done){
// 統(tǒng)一將method方法中的字母轉(zhuǎn)成大寫,后面判斷GET方法時 就簡單點
method = method.toUpperCase();
//IE6的兼容
var xhr = window.XMLHttpRequest
? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
//創(chuàng)建打開一個連接 open
//將對象格式的參數(shù)轉(zhuǎn)為urlencoded模式
//新建一個數(shù)組,使用for循環(huán),將對象格式的參數(shù),
//以(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;
}
//創(chuàng)建打開一個連接
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í)行外部傳進來的回調(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);
});
以上就是如何封裝一個Ajax函數(shù)的詳細內(nèi)容,更多關(guān)于封裝Ajax函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!