复杂的ajax 原生js实现

jerry thinkphp 2015年11月18日 收藏
复杂的ajax实现
复杂的原生js ajax实现,加入了时间超时,超时处理模仿百度的js写的
  1. /**
  2.  * 复杂的ajax封装
  3.  * @version 1.0
  4.  *
  5.  * 用法
  6.  *  var xmlhttp = new YAjax();
  7.  *    xmlhttp.request({
  8.  *         url : "./demo.php",  // get请求时 可以这样写 "./demo.php?name=zhangsan"
  9.  *        method : "POST",
  10.  *        data : "name=李四",  // 支持json传值 {"name":"zhangsan"}  get时不用该参数
  11.  *        receiveType : "html",  // json html or xml
  12.  *        timeout : 3000,  // 3秒
  13.  *        success : function(d) {alert(d);},
  14.  *        error : function(xmlhttp){alert('timeout');}
  15.  *    });
  16.  *
  17.  */
  18. function YAjax() {
  19.     this._self = this;
  20.     this.xmlhttp = this.init();
  21. }

  22. YAjax.prototype = {
  23.     constructor : YAjax,
  24.     
  25.     // 初始化xmlhttpRequest
  26.     init : function() {
  27.         var xmlhttp = null;
  28.     
  29.         // 针对不同浏览器建立这个对象的不同方式写不同代码
  30.         if(window.XMLHttpRequest) {
  31.             xmlhttp = new XMLHttpRequest();
  32.             //针对某些特定版本的Mozillar浏览器的BUG进行修正
  33.             if(xmlhttp.overrideMimeType) {
  34.                 xmlhttp.overrideMimeType("text/xml");
  35.             }
  36.             
  37.         } else if (window.ActiveXObject) {
  38.             var activexName = ['MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
  39.             for (var i=0; i<activexName.length; i++) {
  40.                 try {
  41.                     xmlhttp = new ActiveXObject(activexName[i]);
  42.                     break;
  43.                 } catch(e) {}
  44.             }
  45.         }
  46.     
  47.         return xmlhttp;
  48.     },
  49.     
  50.     extend : function(destination, source, override) {
  51.         if(undefined == override) override = true;
  52.         if(typeof destination != "object" && typeof destination != "function") {
  53.             if(!override) 
  54.                 return destination;
  55.             else 
  56.                 destination = {};
  57.         } 
  58.         var property = '';
  59.         for(property in source) {
  60.             if(override || !(property in destination)) {
  61.                 destination[property] = source[property];
  62.             }
  63.         }
  64.     
  65.         return destination;    
  66.     },
  67.     
  68.     // json to string {name: 'lisi', age: 10} --> name=lisi&age=10
  69.     json2String : function(jsonData) {
  70.         var strArr = [];
  71.         for(var k in jsonData) {
  72.             strArr.push(+ "=" + jsonData[k]);    
  73.         }
  74.             
  75.         return strArr.join("&");
  76.     },
  77.     
  78.     // 发送http 请求
  79.     request : function(opt) {
  80.         var _self = this,
  81.             isTimeout = false,
  82.             timeFlag = 0,
  83.             options = {
  84.                 url : "",   // string
  85.                 data : "",  // json or string
  86.                 method : "POST",
  87.                 receiveType : "html",  // html json or xml
  88.                 timeout : 7000,
  89.                 async : true,
  90.                 success : function(){alert("define your success function");},
  91.                 error : function(xmlhttp){}
  92.             };
  93.         if("data" in opt) {
  94.             if(typeof opt.data == "string"){} else {opt.data = this.json2String(opt.data); }    
  95.         }
  96.         options = this.extend(options, opt);
  97.         
  98.         this.xmlhttp.onreadystatechange = function(){
  99.             if(_self.xmlhttp.readyState == 4) {
  100.                 if(!isTimeout && _self.xmlhttp.status == 200) {
  101.                     clearTimeout(timeFlag);
  102.                     var t = options.receiveType.toLowerCase();
  103.                     if(== "html") {
  104.                         options.success(_self.xmlhttp.responseText);
  105.                         
  106.                     } else if(== "xml") {
  107.                         options.success(_self.xmlhttp.responseXML);    
  108.                         
  109.                     } else if(== 'json') {
  110.                         try {
  111.                             var obj = JSON.parse(_self.xmlhttp.responseText);
  112.                             options.success(obj);    
  113.                         } catch(e) {
  114.                             var str = '(' + _self.xmlhttp.responseText + ')';  //json字符串
  115.                             options.success(eval(str));
  116.                         }
  117.                     } else {}
  118.                     
  119.                 } else {
  120.                     clearTimeout(timeFlag);
  121.                     options.error(_self.xmlhttp);
  122.                 }
  123.             }
  124.         };
  125.         
  126.         timeFlag = setTimeout(function(){
  127.             if(_self.xmlhttp.readyState != 4) {
  128.                 isTimeout = true;
  129.                 _self.xmlhttp.abort();
  130.                 clearTimeout(timeFlag);
  131.              }    
  132.         }, options.timeout);
  133.         
  134.         this.xmlhttp.open(options.method.toUpperCase(), options.url, options.async);  //打开与服务器连接
  135.         if(options.method.toUpperCase() == "POST") {
  136.             this.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');  //post方式要设置请求类型
  137.             this.xmlhttp.send(options.data);  //发送内容到服务器

  138.         } else {
  139.                 this.xmlhttp.send(null);
  140.         }
  141.     }
  142. };