Kook ajax v1.0

代碼:
  1. /*
  2.  * Ajax 封裝
  3.  *@author Kyle @time 2008-11-12
  4.  *@author Kyle @time 2008-11-13
  5.  *@veision 0.1
  6.  */
  7. var $XhrCreator = false;// XMLHttpRequest 創造器
  8. /**
  9.  * XMLHttpRequest 創造器1 用於非MS IE
  10.  * 
  11.  * @return XMLHttpRequest
  12.  */
  13. function xhr1() {
  14.     return new XMLHttpRequest();
  15. }
  16. /**
  17.  * XMLHttpRequest 創造器2 用於MS IE
  18.  * 
  19.  * @return XMLHttpRequest
  20.  */
  21. function xhr2() {
  22.     return new ActiveXObject("Microsoft.XMLHTTP");
  23. }
  24. /**
  25.  * 瀏覽器XMLHttpRequest對象創建工廠
  26.  * 
  27.  * @return XMLHttpRequest 創造器
  28.  */
  29. function XhrCreatorFactory() {
  30.     try {
  31.         xhr1();
  32.         return xhr1;
  33.     } catch (trymicrosoft) {
  34.         try {
  35.             xhr2();
  36.             return xhr2;
  37.         } catch (other) {
  38.             alert('Browser does not support xhr');
  39.             return null;
  40.         }
  41.     }
  42. }
  43. function Ajax(url) {
  44.     /**
  45.      * 如果XMLHttpRequest 創造器未初始化,則通過創造器工廠初始化
  46.      */
  47.     if (!$XhrCreator) {
  48.         $XhrCreator = XhrCreatorFactory();// 初始化XMLHttpRequest 創造器
  49.     }
  50.     this.request = $XhrCreator();// 創建XMLHttpRequest對象
  51.     this.url = url;
  52.     this.ready = function() {
  53.         alert('ready function is null');
  54.     };// 當加載完成回調的函數
  55. }
  56. // 發送請求
  57. Ajax.prototype.send = function() {
  58.     var request = this.request;
  59.     var ready = this.ready;
  60.     request.open("GET"this.url, true);
  61.     function ready() {
  62.         this.ready();
  63.     }
  64.     request.onreadystatechange = function() {
  65.         if (request.readyState == 4)
  66.             if (request.status == 200) {
  67.                 var data = request.responseText;
  68.                 ready(data);
  69.                 // 銷燬XMLHttpRequest對象
  70.             }
  71.     }
  72.     request.send(null);// !ff中間參數不可爲空
  73. }
用法:    
  1. var url='';//請求的url

  2.  var ajax=new Ajax(url);

  3.         //數據加載完畢是時執行
  4.         ajax.ready=function(data){
  5.             // 業務處理       
  6.             ajax=null;//銷燬ajax
  7.             }
  8.         ajax.send();//發送數據
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章