簡單封裝ajax

  1. (function (window) {  
  2.     //避免污染全局變量  
  3.     function ajax(options) {  
  4.         var init = {  
  5.             type: 'get',  
  6.             url: "",  
  7.             data: {},  
  8.             async: true,  
  9.             success: function (txt) {  
  10.             },  
  11.             error: function () {  
  12.             },  
  13.             cache: true,  
  14.             beforeSend: function () {  
  15.             },  
  16.             complete: function () {  
  17.             }  
  18.         };  
  19.         options = merge(init, options);  
  20.         options.data = hb(options.data);  
  21.         var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");  
  22.         //用一個變量來保存是否是post提交方式  值爲布爾值  
  23.         var is_post = /^post$/i.test(options.type);  
  24.         //來判斷是否需要處理url get方式的data需要加到url中  
  25.         if (!is_post) {  
  26.             //沒有考慮到url可能已經有參數  
  27.             //優先級的問題 &的問題  
  28.             options.url += (options.url.indexOf('?') > -1 ? "&" : '?') + options.data;  
  29.             //處理緩存 是否加上時間戳  
  30.             options.url += options.cache ? "" : '&__time__=' + new Date().getTime();  
  31.         }  
  32.         xhr.open(options.type, options.url, options.async);  
  33.         //開始動畫  
  34.         options.beforeSend();  
  35.         //設置頭文件  
  36.         if (is_post) {  
  37.             xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
  38.         }  
  39.         xhr.send(options.data);  
  40.         xhr.onreadystatechange = function () {  
  41.             if (xhr.readyState == 4) {  
  42.   
  43.                 if (xhr.status == 200) {  
  44.                     //提供xhr的使用權限  方便在使用時可以獲取xhr的其他屬性  
  45.                     options.success(xhr.responseText, xhr);  
  46. //                    complete();  
  47.                 } else {  
  48.                     options.error(xhr.status, xhr);  
  49.                 }  
  50.                 options.complete();  
  51.             }  
  52.         }  
  53.   
  54.     }  
  55.     function merge(init, add) {  
  56.         for (var key in add) {  
  57.             if (key in init) {  
  58.                 init[key] = add[key];  
  59.             }  
  60.         }  
  61.         return init;  
  62.     }  
  63.     function hb(obj) {  
  64.         var str = "";  
  65.         for(var key in obj){  
  66.             str+= key+'='+obj[key]+'&';  
  67.         }  
  68.         return str;  
  69.     }  
  70.     window.ajax=ajax;  
  71. })(window);  
發佈了19 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章