ext-base-ajax.js
上传用户:shuoshiled
上传日期:2018-01-28
资源大小:10124k
文件大小:13k
源码类别:

中间件编程

开发平台:

JavaScript

  1. /*!  * Ext JS Library 3.0.0  * Copyright(c) 2006-2009 Ext JS, LLC  * licensing@extjs.com  * http://www.extjs.com/license  */ /*
  2.  * Portions of this file are based on pieces of Yahoo User Interface Library
  3.  * Copyright (c) 2007, Yahoo! Inc. All rights reserved.
  4.  * YUI licensed under the BSD License:
  5.  * http://developer.yahoo.net/yui/license.txt
  6.  */
  7.     Ext.lib.Ajax = function() {     
  8.     var activeX = ['MSXML2.XMLHTTP.3.0',
  9.            'MSXML2.XMLHTTP',
  10.            'Microsoft.XMLHTTP'],
  11.             CONTENTTYPE = 'Content-Type';
  12.            
  13. // private
  14. function setHeader(o) {
  15.         var conn = o.conn,
  16.          prop;
  17.         
  18.         function setTheHeaders(conn, headers){
  19.       for (prop in headers) {
  20.                     if (headers.hasOwnProperty(prop)) {
  21.                         conn.setRequestHeader(prop, headers[prop]);
  22.                     }
  23.                 }   
  24.         }
  25.         
  26.             if (pub.defaultHeaders) {
  27.             setTheHeaders(conn, pub.defaultHeaders);
  28.             }
  29.             if (pub.headers) {
  30. setTheHeaders(conn, pub.headers);
  31.                 pub.headers = null;                
  32.             }
  33.         }    
  34.         
  35.         // private
  36.         function createExceptionObject(tId, callbackArg, isAbort, isTimeout) {         
  37.             return {
  38.             tId : tId,
  39.             status : isAbort ? -1 : 0,
  40.             statusText : isAbort ? 'transaction aborted' : 'communication failure',
  41.                     isAbort: true,
  42.                     isTimeout: true,
  43.             argument : callbackArg
  44.             };
  45.         }  
  46.         
  47.         // private 
  48.         function initHeader(label, value) {         
  49. (pub.headers = pub.headers || {})[label] = value;             
  50.         }
  51.     
  52.         // private
  53.         function createResponseObject(o, callbackArg) {
  54.             var headerObj = {},
  55.                 headerStr,              
  56.                 conn = o.conn,
  57.                 t,
  58.                 s;
  59.             try {
  60.                 headerStr = o.conn.getAllResponseHeaders();   
  61.                 Ext.each(headerStr.replace(/rn/g, 'n').split('n'), function(v){
  62.                     t = v.indexOf(':');
  63.                     if(t >= 0){
  64.                         s = v.substr(0, t).toLowerCase();
  65.                         if(v.charAt(t + 1) == ' '){
  66.                             ++t;
  67.                         }
  68.                         headerObj[s] = v.substr(t + 1);
  69.                     }
  70.                 });
  71.             } catch(e) {}
  72.                         
  73.             return {
  74.                 tId : o.tId,
  75.                 status : conn.status,
  76.                 statusText : conn.statusText,
  77.                 getResponseHeader : function(header){return headerObj[header.toLowerCase()];},
  78.                 getAllResponseHeaders : function(){return headerStr},
  79.                 responseText : conn.responseText,
  80.                 responseXML : conn.responseXML,
  81.                 argument : callbackArg
  82.             };
  83.         }
  84.         
  85.         // private
  86.         function releaseObject(o) {
  87.             o.conn = null;
  88.             o = null;
  89.         }        
  90.     
  91.         // private
  92.         function handleTransactionResponse(o, callback, isAbort, isTimeout) {
  93.             if (!callback) {
  94.                 releaseObject(o);
  95.                 return;
  96.             }
  97.             var httpStatus, responseObject;
  98.             try {
  99.                 if (o.conn.status !== undefined && o.conn.status != 0) {
  100.                     httpStatus = o.conn.status;
  101.                 }
  102.                 else {
  103.                     httpStatus = 13030;
  104.                 }
  105.             }
  106.             catch(e) {
  107.                 httpStatus = 13030;
  108.             }
  109.             if ((httpStatus >= 200 && httpStatus < 300) || (Ext.isIE && httpStatus == 1223)) {
  110.                 responseObject = createResponseObject(o, callback.argument);
  111.                 if (callback.success) {
  112.                     if (!callback.scope) {
  113.                         callback.success(responseObject);
  114.                     }
  115.                     else {
  116.                         callback.success.apply(callback.scope, [responseObject]);
  117.                     }
  118.                 }
  119.             }
  120.             else {
  121.                 switch (httpStatus) {
  122.                     case 12002:
  123.                     case 12029:
  124.                     case 12030:
  125.                     case 12031:
  126.                     case 12152:
  127.                     case 13030:
  128.                         responseObject = createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false), isTimeout);
  129.                         if (callback.failure) {
  130.                             if (!callback.scope) {
  131.                                 callback.failure(responseObject);
  132.                             }
  133.                             else {
  134.                                 callback.failure.apply(callback.scope, [responseObject]);
  135.                             }
  136.                         }
  137.                         break;
  138.                     default:
  139.                         responseObject = createResponseObject(o, callback.argument);
  140.                         if (callback.failure) {
  141.                             if (!callback.scope) {
  142.                                 callback.failure(responseObject);
  143.                             }
  144.                             else {
  145.                                 callback.failure.apply(callback.scope, [responseObject]);
  146.                             }
  147.                         }
  148.                 }
  149.             }
  150.             releaseObject(o);
  151.             responseObject = null;
  152.         }  
  153.         
  154.         // private
  155.         function handleReadyState(o, callback){
  156.     callback = callback || {};
  157.             var conn = o.conn,
  158.              tId = o.tId,
  159.              poll = pub.poll,
  160. cbTimeout = callback.timeout || null;
  161.             if (cbTimeout) {
  162.                 pub.timeout[tId] = setTimeout(function() {
  163.                     pub.abort(o, callback, true);
  164.                 }, cbTimeout);
  165.             }
  166.             poll[tId] = setInterval(
  167.                 function() {
  168.                     if (conn && conn.readyState == 4) {
  169.                         clearInterval(poll[tId]);
  170.                         poll[tId] = null;
  171.                         if (cbTimeout) {
  172.                             clearTimeout(pub.timeout[tId]);
  173.                             pub.timeout[tId] = null;
  174.                         }
  175.                         handleTransactionResponse(o, callback);
  176.                     }
  177.                 },
  178.                 pub.pollInterval);
  179.         }
  180.         
  181.         // private
  182.         function asyncRequest(method, uri, callback, postData) {
  183.             var o = getConnectionObject() || null;
  184.             if (o) {
  185.                 o.conn.open(method, uri, true);
  186.                 if (pub.useDefaultXhrHeader) {                    
  187.                  initHeader('X-Requested-With', pub.defaultXhrHeader);
  188.                 }
  189.                 if(postData && pub.useDefaultHeader && (!pub.headers || !pub.headers[CONTENTTYPE])){
  190.                     initHeader(CONTENTTYPE, pub.defaultPostHeader);
  191.                 }
  192.                 if (pub.defaultHeaders || pub.headers) {
  193.                     setHeader(o);
  194.                 }
  195.                 handleReadyState(o, callback);
  196.                 o.conn.send(postData || null);
  197.             }
  198.             return o;
  199.         }
  200.         
  201.         // private
  202.         function getConnectionObject() {
  203.             var o;      
  204.             try {
  205.                 if (o = createXhrObject(pub.transactionId)) {
  206.                     pub.transactionId++;
  207.                 }
  208.             } catch(e) {
  209.             } finally {
  210.                 return o;
  211.             }
  212.         }
  213.        
  214.         // private
  215.         function createXhrObject(transactionId) {
  216.             var http;
  217.             
  218.             try {
  219.                 http = new XMLHttpRequest();                
  220.             } catch(e) {
  221.                 for (var i = 0; i < activeX.length; ++i) {             
  222.                     try {
  223.                         http = new ActiveXObject(activeX[i]);                        
  224.                         break;
  225.                     } catch(e) {}
  226.                 }
  227.             } finally {
  228.                 return {conn : http, tId : transactionId};
  229.             }
  230.         }
  231.          
  232.     var pub = {
  233.         request : function(method, uri, cb, data, options) {
  234.     if(options){
  235.         var me = this,         
  236.          xmlData = options.xmlData,
  237.          jsonData = options.jsonData,
  238.                         hs;
  239.         
  240.         Ext.applyIf(me, options);         
  241.             
  242.             if(xmlData || jsonData){
  243.                         hs = me.headers;
  244.                         if(!hs || !hs[CONTENTTYPE]){
  245.                 initHeader(CONTENTTYPE, xmlData ? 'text/xml' : 'application/json');
  246.                         }
  247.             data = xmlData || (Ext.isObject(jsonData) ? Ext.encode(jsonData) : jsonData);
  248.         }
  249.     }          
  250.     return asyncRequest(method || options.method || "POST", uri, cb, data);
  251.         },
  252.         serializeForm : function(form) {
  253.         var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements,
  254.              hasSubmit = false,
  255.              encoder = encodeURIComponent,
  256.          element,
  257.              options, 
  258.              name, 
  259.              val,             
  260.              data = '',
  261.              type;
  262.             
  263.         Ext.each(fElements, function(element) {             
  264.                 name = element.name;              
  265. type = element.type;
  266.                 if (!element.disabled && name){
  267.                 if(/select-(one|multiple)/i.test(type)){                 
  268.             Ext.each(element.options, function(opt) {
  269.             if (opt.selected) {
  270.             data += String.format("{0}={1}&",                 
  271.               encoder(name),               
  272.                (opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttributeNode('value').specified) ? opt.value : opt.text);
  273.                                 }
  274.                             });
  275.                 } else if(!/file|undefined|reset|button/i.test(type)) {
  276.                 if(!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)){
  277.                                     
  278.                                 data += encoder(name) + '=' + encoder(element.value) + '&';                     
  279.                                 hasSubmit = /submit/i.test(type);    
  280.                             }                  
  281.                 } 
  282.                 }
  283.             });            
  284.             return data.substr(0, data.length - 1);
  285.         },
  286.         
  287.         useDefaultHeader : true,
  288.         defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
  289.         useDefaultXhrHeader : true,
  290.         defaultXhrHeader : 'XMLHttpRequest',        
  291.         poll : {},
  292.         timeout : {},
  293.         pollInterval : 50,
  294.         transactionId : 0,
  295.         
  296. // This is never called - Is it worth exposing this?           
  297. //          setProgId : function(id) {
  298. //              activeX.unshift(id);
  299. //          },
  300. // This is never called - Is it worth exposing this?  
  301. //          setDefaultPostHeader : function(b) {
  302. //              this.useDefaultHeader = b;
  303. //          },
  304.         
  305. // This is never called - Is it worth exposing this?  
  306. //          setDefaultXhrHeader : function(b) {
  307. //              this.useDefaultXhrHeader = b;
  308. //          },
  309. // This is never called - Is it worth exposing this?        
  310. //          setPollingInterval : function(i) {
  311. //              if (typeof i == 'number' && isFinite(i)) {
  312. //                  this.pollInterval = i;
  313. //              }
  314. //          },
  315.         
  316. // This is never called - Is it worth exposing this?
  317. //          resetDefaultHeaders : function() {
  318. //              this.defaultHeaders = null;
  319. //          },
  320.         abort : function(o, callback, isTimeout) {
  321.         var me = this,
  322.          tId = o.tId,
  323.          isAbort = false;
  324.         
  325.             if (me.isCallInProgress(o)) {
  326.                 o.conn.abort();
  327.                 clearInterval(me.poll[tId]);
  328.                 me.poll[tId] = null;
  329.                 if (isTimeout) {
  330.                     me.timeout[tId] = null;
  331.                 }
  332.                 handleTransactionResponse(o, callback, (isAbort = true), isTimeout);                
  333.             }
  334.             return isAbort;
  335.         },
  336.         isCallInProgress : function(o) {
  337.             // if there is a connection and readyState is not 0 or 4
  338.             return o.conn && !{0:true,4:true}[o.conn.readyState];         
  339.         }
  340.     };
  341.     return pub;
  342.     }();