文章詳情頁(yè)
如何封裝一個(gè)Ajax函數(shù)
瀏覽:229日期:2022-06-11 15:14:52
目錄
- 如何封裝Ajax函數(shù)
- 封裝自己的 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} 請(qǐng)求方法--method
參數(shù)2:{string} 請(qǐng)求地址--url
參數(shù)3:{object} 請(qǐng)求參數(shù)--params
參數(shù)4:{function} 請(qǐng)求完成后,執(zhí)行的回調(diào)函數(shù)--done
function ajax(method,url,params,done){ // 統(tǒng)一將method方法中的字母轉(zhuǎn)成大寫,后面判斷GET方法時(shí) 就簡(jiǎn)單點(diǎn) method = method.toUpperCase(); //IE6的兼容 var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); //創(chuàng)建打開一個(gè)連接 open //將對(duì)象格式的參數(shù)轉(zhuǎn)為urlencoded模式 //新建一個(gè)數(shù)組,使用for循環(huán),將對(duì)象格式的參數(shù), //以(id = 1)的形式,每一個(gè)鍵值對(duì)用 & 符號(hào)連接 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è)置請(qǐng)求頭、請(qǐng)求體 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)來(lái)的回調(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); });
以上就是如何封裝一個(gè)Ajax函數(shù)的詳細(xì)內(nèi)容,更多關(guān)于封裝Ajax函數(shù)的資料請(qǐng)關(guān)注其它相關(guān)文章!
標(biāo)簽:
Ajax
相關(guān)文章:
排行榜
