原生封裝的ajax

來源:互聯網
上載者:User

標籤:urlencode   microsoft   ready   緩衝   orm   ati   cat   事件   ros   

原生封裝的ajax的代碼如下:

//將資料轉換成 a=1&b=2格式;

function json2url(json){

   var arr = [];

   //加隨機數防止緩衝;

   json.t = Math.random();

   for(var name in json){

      arr.push(name+‘=‘+json[name]);

   }

   return arr.join(‘&‘);

}

 

function ajax(json){

   //1.建立一個ajax對象;

   if(window.XMLHttpRequest){

      var oAjax = new XMLHttpRequest();

   }else{

      var oAjax = new ActiveXObject(‘Microsoft.XMLHTTP‘);

   }

 

   //考慮預設值:

   if(!json.url){

      alert(‘請輸入合理的請求地址!‘);

      return;

   }

   json.type = json.type || ‘get‘;

   json.time = json.time || 5000;

   json.data = json.data || {};

 

   //判斷使用者傳遞的是get還是post請求:

   switch (json.type.toLowerCase()){

      case ‘get‘:

         //2.開啟請求;

         oAjax.open(‘get‘,json.url+‘?‘+json2url(json.data),true);

         //3.發送資料:

         oAjax.send();

         break;

      case ‘post‘:

         //開啟請求;

         oAjax.open(‘post‘,json.url,true);

         //佈建要求頭;

         oAjax.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘);

         //發送資料;

         oAjax.send(json2url(json.data));

   }

   //4.擷取響應資料

   oAjax.onreadystatechange = function() {

      if (oAjax.readyState == 4) {

         if (oAjax.status >= 200 && oAjax.status < 300 || oAjax.status == 304) {

            //如果外邊傳遞了成功的回呼函數,那麼就執行,

            json.success && json.success(oAjax.responseText);

         } else {

            //如果外邊傳遞了失敗的回呼函數,那麼就執行,

            json.error && json.error(oAjax.status);

         }

         clearTimeout(timer);//規定時間內取到資料後清除定時器;

      }

   };

   var timer;

   timer = setTimeout(function(){//設定網路響應逾時;

      alert(‘網路響應逾時,請稍後再試‘);

      oAjax.onreadystatechange = null;//網路逾時後清除事件;

   },json.time);

}

 希望對大家有用

原生封裝的ajax

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.