Ajax类应用示例代码

来源:互联网 发布:51duino源码 编辑:程序博客网 时间:2024/05/17 21:30
  1. /*********************************************************************************************
  2.  Ajax类应用示例代码:
  3.  new Ajax({
  4.      url: 'readMessageList.action',
  5.      onComplete: function(data){document.getElementById('message_div').innerHTML += data;}
  6.  }).doRequest();
  7. **********************************************************************************************/
  8. Ajax = function(config)
  9. {
  10.     this._xmlHttpRequest = null;
  11.     this._userConfig = config;
  12.     this._config = {
  13.         method: 'get',      // get||post|| ...
  14.         async: true,
  15.         returnDataFormat: 'jsCode',     // jsCode||string||xml
  16.         url: null,
  17.         onComplete: function(data){}
  18.     };
  19.     this._init = function()
  20.     {
  21.         if (window.XMLHttpRequest) {
  22.             this._xmlHttpRequest = window.XMLHttpRequest;
  23.         }
  24.         else {
  25.             this._xmlHttpRequest = new ActiveXObject('Microsoft.XMLHTTP');
  26.         }
  27.         
  28.     };
  29.     
  30.     this.doRequest = function()
  31.     {
  32.         var instance = this;
  33.         if (!this._xmlHttpRequest) {
  34.             this._init();
  35.         }
  36.         if (this._userConfig) {
  37.             for (var key in this._userConfig) {
  38.                 this._config[key] = this._userConfig[key];
  39.             }
  40.         }
  41.         this._xmlHttpRequest.open(this._config.method, this._config.url, this._config.async);
  42.         this._xmlHttpRequest.onreadystatechange = function()
  43.         {
  44.             if (instance._xmlHttpRequest.readyState == 4){
  45.                 if (instance._xmlHttpRequest.status == 200){
  46.                     var responseText = instance._xmlHttpRequest.responseText;
  47.                     if (instance._config.returnDataFormat == 'jsCode') {
  48.                         instance._config.onComplete(eval('(' + responseText + ')'));
  49.                     }
  50.                     else if (instance._config.returnDataFormat == 'string') {
  51.                         instance._config.onComplete(responseText);
  52.                     }
  53.                     else if (instance._config.returnDataFormat == 'xml'){
  54.                         instance._config.onComplete(instance._xmlHttpRequest.responseXml);
  55.                     }
  56.                 }
  57.             }
  58.             
  59.         };
  60.         instance._xmlHttpRequest.send(null);
  61.     }
  62. }
原创粉丝点击