PageRenderTime 26ms CodeModel.GetById 9ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/hippo/src/main/webapp/ext/src/adapter/core/ext-base-ajax.js

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