AJAX編程-封裝ajax工具函數

來源:互聯網
上載者:User

標籤:

即 Asynchronous [e‘s??kr?n?s] Javascript And XML,AJAX 不是一門的新的語言,而是對現有技術的綜合利用。
本質是在HTTP協議的基礎上以非同步方式與伺服器進行通訊。

XMLHttpRequest可以以非同步方式的處理常式,瀏覽器內建對象,用於在後台與伺服器通訊(交換資料) ,由此我們便可實現對網頁的部分更新,而不是重新整理整個頁面。

封裝ajax工具函數

$.ajax = function(options){

   if(!options) return false;

  /*options 參數傳遞*/
  var type = options.type || ‘get‘;
  var url = options.url || location.pathname;
  var async = options.async === false ? false : true;
  var data = options.data || {};

/*data 選要轉化成 name=xjj&age=10*/
  var dataStr = ‘‘;
  for(var key in data){
  //console.log(data[key]);
  dataStr += key+‘=‘+data[key]+‘&‘;
  }

/*如果就資料 就裁剪掉最後一個&*/
  dataStr = dataStr && dataStr.slice(0,-1);


  /*ajax 編程*/
  /*初始化*/
  var xhr = new XMLHttpRequest();

  /*請求行*/
  /*如果是get請求那麼就要拼接資料在url後面 ?*/
  xhr.open(type,type == ‘get‘?url+‘?‘+dataStr:url,async);

  /*要求標頭*/
  /*如果是post請求需要設定 content-type application/x-www-form-urlencoded*/
  if(type == ‘post‘){
  xhr.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);
  }

  options.beforeSend && options.beforeSend();

  /*請求主體*/
  /*如果是post請求需要把資料字元傳過去 否則是null*/
  xhr.send(type==‘get‘?null:dataStr);

  /*監聽響應狀態的改變*/
  xhr.onreadystatechange = function(){
  /*響應成功*/
  if(xhr.readyState == 4){
    if( xhr.status == 200){
    /*處理響應成功函數*/
      var result = ‘‘;
      /*接受資料*/
      /* json xml string*/
      var contentType = xhr.getResponseHeader(‘Content-Type‘);

      if(contentType.indexOf(‘xml‘) > -1){
      /*服務端返回的是xml資料格式*/
        result = xhr.responseXML;
       }else if(contentType.indexOf(‘json‘) > -1){
        /*服務端返回的是json資料格式*/
        /*json字串*/
        var str = xhr.responseText;
        result = JSON.parse(str);
       }else{
      result = xhr.responseText;
      }

    /*調用回呼函數*/
      options.success && options.success(result);
    }
  /*響應失敗*/
  else{
    /*處理響應失敗函數*/
  options.error && options.error(‘request fail code‘ + xhr.status);
    }

  options.complete && options.complete();
  }
 }
};



AJAX編程-封裝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.