如何封裝一個Ajax函數(shù)
如何封裝ajax函數(shù)
一個ajax函數(shù):
// 一個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方法時 就簡單點 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方法 還需要設置請求頭、請求體 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ù)即可 // 需要用到響應體 } } //調(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)容,更多關于封裝ajax函數(shù)的資料請關注碩編程其它相關文章!