DIV CSS 佈局教程網

ajax框架封裝
編輯:AJAX詳解     
自己封裝了一個AJax框架。希望能給讀者參考、幫助、評價。

自從提出WEB2.0富客戶以後AJAX技術現在是越來越流行,有待代替CS桌面程序之勢。以前開發用了很多AJAX的技術比如EXT,prototype,jQuery等等,但都是開源封裝好的AJAX框架。從沒真正用過純正的AJAX,故參照prototyp面向對象思想自己封裝了一個AJax框架。希望能給讀者參考、幫助、評價。

/*
 * 自己封裝的AJax
 *
 * 
 * @author JSong
 * @version 1.00 $date:2009-07-02
 *
 * history:
 *
 */
 
 Object.extend = function(destination, source) {
  for (var property in source) {
     destination[property] = source[property];
   }
  return destination;
 };
 
 Object.extend(String.prototype, {
  include: function(pattern) {
     return this.indexOf(pattern) > -1;
   },
   startsWith: function(pattern) {
     return this.indexOf(pattern) == 0;
   },
   endsWith: function(pattern) {
     return this.lastIndexOf(pattern) == (this.length - pattern.length);
   },
   empty: function() {
     return /^\s*$/.test(this) this == undefined this == null;
   }
 });
 
 Object.extend(Array.prototype, {
   each: function(iterator) {
    try {
      for (var i = 0, length = this.length; i < length; i++) {
         iterator(this[i]);
      }
     } catch (e) {
        if (e != 'break') { throw e };
     }
   },
   clear: function() {
     this.length = 0;
     return this;
   },
   first: function() {
     return this[0];
   },
   last: function() {
     return this[this.length - 1];
   },
   indexOf: function(object) {
     for (var i = 0, length = this.length; i < length; i++) {
        if (this[i] == object) {return i};
     }
     return -1;
   },
   size: function() {
     return this.length;
   },
   include: function(object) {
     var found = false;
     this.each(function(value) {
        if (value == object) {found = true; throw 'break';}
     });
     return found;
   }
 });
 
 function $(element) {
 if(arguments.length > 1) {
  for(var i = 0, elements = [], length = arguments.length; i < length; i++) {
     elements.push($(arguments[i]));
  }
  return elements;
 }
 if(typeof element == 'string') {
  element = document.getElementById(element);
 }
 return element;
 };
 
 var AJax = {
  transport: new Object(),
  options: new Object(),
  getTransport: function() {
  if(window.ActiveXObject) {
   try {
    return new ActiveXObject('Msxm12.XMLHTTP');
   } catch(e) {
    try {
      return new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) {}
   }
  } else if(window.XMLHttpRequest) {
   try {
    return new XMLHttpRequest();
   } catch(e) {}
  }
  },
  setOptions: function(options) {
  AJax.options = {
   method:       'get',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'utf-8',
      parameters:   ''
     };
     Object.extend(AJax.options, options);
     ajax.options.method = AJax.options.method.toUpperCase();
  },
  request: function(url, options) {
   ajax.transport = AJax.getTransport();
   AJax.setOptions(options);
   this.method = AJax.options.method;
   var params = AJax.options.parameters;
   if (!['GET', 'POST'].include(this.method)) {
        this.method = 'GET';
     }
     if (this.method == 'GET') {
      url = AJax.setParameters(url, params);
     }
     try {
      ajax.transport.open(this.method, url, AJax.options.asynchronous);
      ajax.transport.onreadystatechange = AJax.stateChange;
      AJax.setRequestHeaders();
      this.body = this.method == 'POST' ? params : null;
        AJax.transport.send(this.body);
   } catch (e) {}
  },
  stateChange: function() {
  try {
   var readyState = AJax.transport.readyState;
   if(readyState == 4) {
    var status = ajax.transport.status, transport = ajax, JSon = AJax.evalJSON();
    if(status == 200) {
     AJax.options['onSuccess'](transport, JSon);
    } else {
     AJax.options['onFailure'](transport, JSon);
    }
   }
  } catch (e) {}
    },
  setParameters: function(url, params) {
  if (params && typeof params == 'string') {
   url += (url.include('?') ? '&' : '?') + params;
  } else if (params && typeof params == 'object') {
    for(var param in params) {
     url += (url.include('?') ? '&' : '?') + param + '=' + params[param];
    }
   }
   return url;
  },
  setRequestHeaders: function() {
     var headers = {
        'X-Requested-With': 'XMLHttpRequest',
        'Accept': 'application/xml, text/XML, text/Html, text/javascript, application/Javascript, application/JSon, text/Javascript, text/plain, */*',
        'If-ModifIEd-Since': 'Thu, 01 Jan 1970 00:00:00 GMT'
     };
     this.method = AJax.options.method;
     if (this.method == 'POST') {
        headers['Content-type'] = AJax.options.contentType +
         (ajax.options.encoding ? '; charset=' + AJax.options.encoding : '');
         if (AJax.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) [0,2005])[1] < 2005) {
             headers['Connection'] = 'close';
         }
     }
     for (var name in headers) {
        AJax.transport.setRequestHeader(name, headers[name]);
     }
   },
   evalJSON: function() {
     try {
        return eval('(' + AJax.transport.responseText + ')');
     } catch (e) {}
   }
 };
 
 var Form = {
  serialize: function(element) {
     var elements = $(element).all;
     var queryComponents = [];
        for(var i = 0; i < elements.length; i++) {
      var parameter = null, method = elements[i].tagName.toLowerCase();
      if(['input', 'select', 'textarea'].include(method)) {
       parameter = Form.Serializers[method](elements[i]);
      }
      if(parameter != null && parameter.constructor == Array) {
         var key = encodeURIComponent(parameter[0]);
         var value = encodeURIComponent(parameter[1]);
       queryComponents.push(key + '=' + value);
      }
        }
     return queryComponents.join('&');
  },
  request: function(options) {
     var params = this.toQueryParams(options.parameters);
     options.parameters = this.serialize(this.form);
     if(params) {
      options.parameters = options.parameters.concat('&' + params);
     }
     if($(this.form).method) {
        options.method = $(this.form).method;
     }
     return new AJax.request($(this.form).action, options);
  },
  toQueryParams: function(params) {
   var queryComponents = [];
   if (params && typeof params == 'string') {
   queryComponents.push(encodeURIComponent(params));
  } else if (params && typeof params == 'object') {
    for(var param in params) {
     var key = encodeURIComponent(param);
         var value = encodeURIComponent(params[param]);
       queryComponents.push(key + '=' + value);
    }
   }
   return queryComponents.join('&');
  }
 };
 
 Form.Serializers = {
  input: function(element) {
     switch(element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          return this.inputSelector(element);
        default:
          return this.textarea(element);
     }
  },
  inputSelector: function(element) {
     if(element.checked) {
        return [element.name, element.value];
     }
   },
   textarea: function(element) {
     return [element.name, element.value];
   },
   select: function(element) {
     return this[element.type == 'select-one' ?
        'selectOne' : 'selectMany'](element);
   },
   selectOne: function(element) {
     var value = null, option, index = element.selectedIndex;
     if(index >= 0) {
        option = element.options[index];
        value = option.value == (undefined '') ? option.text : option.value;
     }
     return [element.name, value];
   },
 selectMany: function(element) {
     var value = [];
      for(var i = 0; i < element.length; i++) {
        var option = element.options[i];
        if(option.selected) {
          var optvalue = option.value == (undefined '') ? option.text : option.value;
          value.push(optvalue);
        }
     }
     return [element.name, value];
  }
 };
 
 function $F(element) {   
    this.form = element;   
 }   
 
 Object.extend($F.prototype, Form); 

/**************************************************************
 * 測試函數
 */
function onTest() {

 //get提交方法
 var params = new Object();
 params.ss = '張三';
 new ajax.request('AJax.do?method=doGet', {
     onSuccess: function(transport) {    
           alert(transport.evalJSON().xx)  
      },
  parameters: params
 });

//post form提交方法
 var params = new Object();
 params.idd = 1000;
 params.names = '張三'
 new $F('form').request({
      onSuccess: function(transport) {
           alert(transport.evalJSON().xx);
       },
       parameters: params  
 });
}

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved