ajax原理及封裝

  • 2020 年 3 月 29 日
  • 筆記

一:AJAX 簡介

       AJAX 是一種在無需重新載入整個網頁的情況下,能夠更新部分網頁的技術,通過在後台與伺服器進行少量數據交換,AJAX 可以使網頁實現非同步更新。

       AJAX = 非同步 JavaScript 和 XML。

二:AJAX的使用
      1.創建ajax對象:

                                const xhr = new XMLHttpRequest();// IE9及以上
                                const xhr = new ActiveXObject(‘Mricosoft.XMLHTTP’);// IE9以下

      2.配置請求資訊:

                                xhr.open(‘請求方式’, ‘請求地址’, 是否非同步);

                                請求方式 get / post / put / …;請求地址 url;默認true表示非同步,false表示同步。

      3.發送請求:

                                xhr.send();

      4.接收響應:

                        xhr.onload = function () { console.log(xhr.responseText) };

             xhr.onreadyStateChange = function () {if (xhr.readyState === 4 && /^2d{2|$/.test(xhr.status)) {}};其中readyState表示狀態碼,為4即表示成功;stauts是http狀態碼,2系列都表示成功;

三:AJAX封裝

  1.兼容處理:

  創建ajax對象兼容

        var xhr = null;          if(typeof XMLHttpRequest === "function"){              xhr = new XMLHttpRequest();          }else{              xhr = new ActiveXObject("Microsoft.XMLHTTP");          }

  2.程式碼封裝

         function assign(){              var target = arguments[0];              for(var i = 1 ; i < arguments.length ; i ++){                  // console.log(arguments[i]);                  for(var attr in arguments[i]){                      target[attr] = arguments[i][attr];                  }              }              return target;          }            function toUrlData( obj , url , method){              if( isObject(obj) ){                  var str = "";                  for(var attr in obj){                      str += "&" + attr + "=" + obj[attr]                  }                  str = str.slice(1);                  // 如果數據發送方式是POST,那麼直接返回str就可以了;                  method = method || "";                  if( method.toUpperCase() === "POST"){                      return str;                  }                  url += "?" + str;                  return url;              }              return url;          }          function isObject( data ){              return (typeof data === "object" && data !== null && data.constructor && data.constructor === Object)          }          function ajax( options ){              var _default = {                  type : "GET",                  url : "",                  data : null,                  dataType : "text",                  status : null,                  success : function(){},                  complete : function(){},                  error : function(){}              }              // 我們會創建一些默認參數, 如果用戶傳入了其他數據會對默認參數進行覆蓋;              options = assign( _default , options );              options.type = options.type.toLowerCase();                if( isObject(options.context) ){                  var callback_list = ["success","complete","error"];                  callback_list.forEach( function( item ){                      // console.log(options[item]);                      options[item] = options[item].bind( options.context );                  })              }                // 1. 創建shr ;              var xhr = null;              if(typeof XMLHttpRequest === "function"){                  xhr = new XMLHttpRequest();              }else{                  xhr = new ActiveXObject("Microsoft.XMLHTTP");              }              // 1. 如果請求方式為get,那麼我們把數據拼接到url上;              if(options.type === "get"){                  options.url =  toUrlData( options.data , options.url , options.type)              }              // 2. 如果請求方式為post,那麼我們把數據拼接到data上;              if(options.type === "post"){                  options.data =  toUrlData( options.data , options.url , options.type)              }              // 2. 根據數據進行方法的調用;              xhr.open( options.type , options.url , true ) ;              options.type === "post" ? xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") : "";              // 3. 調用send方法;              xhr.send( options.type=== "get" ? null : options.data );              // 4. 調用回調函數;              xhr.onreadystatechange = function(){                  // xhr程式運行結束;                  if( xhr.readyState === 4 ){                      options.complete();                      if( /^2d{2}$/.test(xhr.status) ){                          // 5.傳遞數據                            try{                              var res = options.dataType === "json" ? JSON.parse(xhr.responseText) : xhr.responseText;                              options.success(res);                          }catch(e){                              options.error(e,xhr.status);                          }                      }else{                          options.error("error",xhr.status);                      }                      // 策略模式調用 :                       if( isObject(options.status) ){                          typeof options.status[xhr.status] === "function" ? options.status[xhr.status]() : "";                      }                  }              }          }