// 封裝ajax請求函數(shù)
// obj { url,method,data,dataType,fn}
function ajax(obj){
? // 判斷是否有傳遞url
? if(!obj.url){
? ? throw Error('請求地址不能為空');
? }
? // 準(zhǔn)備一個默認的參數(shù)對象
? let info = {
? ? method:'get',
? ? data:{},
? ? dataType:'string',
? ? fn:function(){}
? }
? // 將傳入的對象參數(shù)替換掉默認參數(shù)對象中的值
? for (const attr in obj) {
? ? info[attr] = obj[attr];
? }
? // 拼接參數(shù)
? //? 拼接為鍵值對的字符串
? let strVal = ''
? for (const key in info.data) {
? ? strVal += `${key}=${info.data[key]}&`;
? }
? // console.log(strVal); // name=leon&age=18&
? strVal = strVal.slice(0,-1);// 截取字符串中除了最后一個支字符
? // 1. 創(chuàng)建ajax對象
? const xhr = new XMLHttpRequest();
? // 判斷是否是get請求
? // 2. 配置請求方式和地址
? // 3. 發(fā)送請求
? if(info.method.toUpperCase() === 'GET'){
? ? xhr.open('get',`${info.url}?${strVal}`);
? ? xhr.send();
? }else{
? ? xhr.open('post',info.url);
? ? // post請求配置請求頭
? ? xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
? ? xhr.send(strVal)
? }
? // 接受響應(yīng)
? xhr.onreadystatechange = function(){
? ? // 當(dāng)http狀態(tài)碼為200 ajax狀態(tài)碼4
? ? if(xhr.status == 200 && xhr.readyState == 4){
? ? ? // 判斷是否需要JSON轉(zhuǎn)換
? ? ? if(info.dataType == 'json'){
? ? ? ? var res = JSON.parse(xhr.responseText);
? ? ? }else{
? ? ? ? var res = xhr.responseText;
? ? ? }
? ? ? // 接受到參數(shù)后的回調(diào)函數(shù)
? ? ? info.fn(res);
? ? }
? }
}