Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / data / Connection.js
1 /**
2  * @class Ext.data.Connection
3  * The Connection class encapsulates a connection to the page's originating domain, allowing requests to be made either
4  * to a configured URL, or to a URL specified at request time.
5  *
6  * Requests made by this class are asynchronous, and will return immediately. No data from the server will be available
7  * to the statement immediately following the {@link #request} call. To process returned data, use a success callback
8  * in the request options object, or an {@link #requestcomplete event listener}.
9  *
10  * <p><u>File Uploads</u></p>
11  *
12  * File uploads are not performed using normal "Ajax" techniques, that is they are not performed using XMLHttpRequests.
13  * Instead the form is submitted in the standard manner with the DOM &lt;form&gt; element temporarily modified to have its
14  * target set to refer to a dynamically generated, hidden &lt;iframe&gt; which is inserted into the document but removed
15  * after the return data has been gathered.
16  *
17  * The server response is parsed by the browser to create the document for the IFRAME. If the server is using JSON to
18  * send the return object, then the Content-Type header must be set to "text/html" in order to tell the browser to
19  * insert the text unchanged into the document body.
20  *
21  * Characters which are significant to an HTML parser must be sent as HTML entities, so encode "&lt;" as "&amp;lt;", "&amp;" as
22  * "&amp;amp;" etc.
23  *
24  * The response text is retrieved from the document, and a fake XMLHttpRequest object is created containing a
25  * responseText property in order to conform to the requirements of event handlers and callbacks.
26  *
27  * Be aware that file upload packets are sent with the content type multipart/form and some server technologies
28  * (notably JEE) may require some custom processing in order to retrieve parameter names and parameter values from the
29  * packet content.
30  *
31  * Also note that it's not possible to check the response code of the hidden iframe, so the success handler will ALWAYS fire.
32  */
33 Ext.define('Ext.data.Connection', {
34     mixins: {
35         observable: 'Ext.util.Observable'
36     },
37
38     statics: {
39         requestId: 0
40     },
41
42     url: null,
43     async: true,
44     method: null,
45     username: '',
46     password: '',
47
48     /**
49      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
50      * @type Boolean
51      */
52     disableCaching: true,
53
54     /**
55      * @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching
56      * through a cache buster. Defaults to '_dc'
57      * @type String
58      */
59     disableCachingParam: '_dc',
60
61     /**
62      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
63      */
64     timeout : 30000,
65
66     /**
67      * @param {Object} extraParams (Optional) Any parameters to be appended to the request.
68      */
69
70     useDefaultHeader : true,
71     defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
72     useDefaultXhrHeader : true,
73     defaultXhrHeader : 'XMLHttpRequest',
74
75     constructor : function(config) {
76         config = config || {};
77         Ext.apply(this, config);
78
79         this.addEvents(
80             /**
81              * @event beforerequest
82              * Fires before a network request is made to retrieve a data object.
83              * @param {Connection} conn This Connection object.
84              * @param {Object} options The options config object passed to the {@link #request} method.
85              */
86             'beforerequest',
87             /**
88              * @event requestcomplete
89              * Fires if the request was successfully completed.
90              * @param {Connection} conn This Connection object.
91              * @param {Object} response The XHR object containing the response data.
92              * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
93              * for details.
94              * @param {Object} options The options config object passed to the {@link #request} method.
95              */
96             'requestcomplete',
97             /**
98              * @event requestexception
99              * Fires if an error HTTP status was returned from the server.
100              * See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Status Code Definitions</a>
101              * for details of HTTP status codes.
102              * @param {Connection} conn This Connection object.
103              * @param {Object} response The XHR object containing the response data.
104              * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
105              * for details.
106              * @param {Object} options The options config object passed to the {@link #request} method.
107              */
108             'requestexception'
109         );
110         this.requests = {};
111         this.mixins.observable.constructor.call(this);
112     },
113
114     /**
115      * <p>Sends an HTTP request to a remote server.</p>
116      * <p><b>Important:</b> Ajax server requests are asynchronous, and this call will
117      * return before the response has been received. Process any returned data
118      * in a callback function.</p>
119      * <pre><code>
120 Ext.Ajax.request({
121 url: 'ajax_demo/sample.json',
122 success: function(response, opts) {
123   var obj = Ext.decode(response.responseText);
124   console.dir(obj);
125 },
126 failure: function(response, opts) {
127   console.log('server-side failure with status code ' + response.status);
128 }
129 });
130      * </code></pre>
131      * <p>To execute a callback function in the correct scope, use the <tt>scope</tt> option.</p>
132      * @param {Object} options An object which may contain the following properties:<ul>
133      * <li><b>url</b> : String/Function (Optional)<div class="sub-desc">The URL to
134      * which to send the request, or a function to call which returns a URL string. The scope of the
135      * function is specified by the <tt>scope</tt> option. Defaults to the configured
136      * <tt>{@link #url}</tt>.</div></li>
137      * <li><b>params</b> : Object/String/Function (Optional)<div class="sub-desc">
138      * An object containing properties which are used as parameters to the
139      * request, a url encoded string or a function to call to get either. The scope of the function
140      * is specified by the <tt>scope</tt> option.</div></li>
141      * <li><b>method</b> : String (Optional)<div class="sub-desc">The HTTP method to use
142      * for the request. Defaults to the configured method, or if no method was configured,
143      * "GET" if no parameters are being sent, and "POST" if parameters are being sent.  Note that
144      * the method name is case-sensitive and should be all caps.</div></li>
145      * <li><b>callback</b> : Function (Optional)<div class="sub-desc">The
146      * function to be called upon receipt of the HTTP response. The callback is
147      * called regardless of success or failure and is passed the following
148      * parameters:<ul>
149      * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
150      * <li><b>success</b> : Boolean<div class="sub-desc">True if the request succeeded.</div></li>
151      * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.
152      * See <a href="http://www.w3.org/TR/XMLHttpRequest/">http://www.w3.org/TR/XMLHttpRequest/</a> for details about
153      * accessing elements of the response.</div></li>
154      * </ul></div></li>
155      * <li><a id="request-option-success"></a><b>success</b> : Function (Optional)<div class="sub-desc">The function
156      * to be called upon success of the request. The callback is passed the following
157      * parameters:<ul>
158      * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
159      * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
160      * </ul></div></li>
161      * <li><b>failure</b> : Function (Optional)<div class="sub-desc">The function
162      * to be called upon failure of the request. The callback is passed the
163      * following parameters:<ul>
164      * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
165      * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
166      * </ul></div></li>
167      * <li><b>scope</b> : Object (Optional)<div class="sub-desc">The scope in
168      * which to execute the callbacks: The "this" object for the callback function. If the <tt>url</tt>, or <tt>params</tt> options were
169      * specified as functions from which to draw values, then this also serves as the scope for those function calls.
170      * Defaults to the browser window.</div></li>
171      * <li><b>timeout</b> : Number (Optional)<div class="sub-desc">The timeout in milliseconds to be used for this request. Defaults to 30 seconds.</div></li>
172      * <li><b>form</b> : Element/HTMLElement/String (Optional)<div class="sub-desc">The <tt>&lt;form&gt;</tt>
173      * Element or the id of the <tt>&lt;form&gt;</tt> to pull parameters from.</div></li>
174      * <li><a id="request-option-isUpload"></a><b>isUpload</b> : Boolean (Optional)<div class="sub-desc"><b>Only meaningful when used
175      * with the <tt>form</tt> option</b>.
176      * <p>True if the form object is a file upload (will be set automatically if the form was
177      * configured with <b><tt>enctype</tt></b> "multipart/form-data").</p>
178      * <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
179      * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
180      * DOM <tt>&lt;form></tt> element temporarily modified to have its
181      * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
182      * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
183      * but removed after the return data has been gathered.</p>
184      * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
185      * server is using JSON to send the return object, then the
186      * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
187      * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
188      * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
189      * is created containing a <tt>responseText</tt> property in order to conform to the
190      * requirements of event handlers and callbacks.</p>
191      * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
192      * and some server technologies (notably JEE) may require some custom processing in order to
193      * retrieve parameter names and parameter values from the packet content.</p>
194      * </div></li>
195      * <li><b>headers</b> : Object (Optional)<div class="sub-desc">Request
196      * headers to set for the request.</div></li>
197      * <li><b>xmlData</b> : Object (Optional)<div class="sub-desc">XML document
198      * to use for the post. Note: This will be used instead of params for the post
199      * data. Any params will be appended to the URL.</div></li>
200      * <li><b>jsonData</b> : Object/String (Optional)<div class="sub-desc">JSON
201      * data to use as the post. Note: This will be used instead of params for the post
202      * data. Any params will be appended to the URL.</div></li>
203      * <li><b>disableCaching</b> : Boolean (Optional)<div class="sub-desc">True
204      * to add a unique cache-buster param to GET requests.</div></li>
205      * </ul></p>
206      * <p>The options object may also contain any other property which might be needed to perform
207      * postprocessing in a callback because it is passed to callback functions.</p>
208      * @return {Object} request The request object. This may be used
209      * to cancel the request.
210      */
211     request : function(options) {
212         options = options || {};
213         var me = this,
214             scope = options.scope || window,
215             username = options.username || me.username,
216             password = options.password || me.password || '',
217             async,
218             requestOptions,
219             request,
220             headers,
221             xhr;
222
223         if (me.fireEvent('beforerequest', me, options) !== false) {
224
225             requestOptions = me.setOptions(options, scope);
226
227             if (this.isFormUpload(options) === true) {
228                 this.upload(options.form, requestOptions.url, requestOptions.data, options);
229                 return null;
230             }
231
232             // if autoabort is set, cancel the current transactions
233             if (options.autoAbort === true || me.autoAbort) {
234                 me.abort();
235             }
236
237             // create a connection object
238             xhr = this.getXhrInstance();
239
240             async = options.async !== false ? (options.async || me.async) : false;
241
242             // open the request
243             if (username) {
244                 xhr.open(requestOptions.method, requestOptions.url, async, username, password);
245             } else {
246                 xhr.open(requestOptions.method, requestOptions.url, async);
247             }
248
249             headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
250
251             // create the transaction object
252             request = {
253                 id: ++Ext.data.Connection.requestId,
254                 xhr: xhr,
255                 headers: headers,
256                 options: options,
257                 async: async,
258                 timeout: setTimeout(function() {
259                     request.timedout = true;
260                     me.abort(request);
261                 }, options.timeout || me.timeout)
262             };
263             me.requests[request.id] = request;
264
265             // bind our statechange listener
266             if (async) {
267                 xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
268             }
269
270             // start the request!
271             xhr.send(requestOptions.data);
272             if (!async) {
273                 return this.onComplete(request);
274             }
275             return request;
276         } else {
277             Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
278             return null;
279         }
280     },
281
282     /**
283      * Upload a form using a hidden iframe.
284      * @param {Mixed} form The form to upload
285      * @param {String} url The url to post to
286      * @param {String} params Any extra parameters to pass
287      * @param {Object} options The initial options
288      */
289     upload: function(form, url, params, options){
290         form = Ext.getDom(form);
291         options = options || {};
292
293         var id = Ext.id(),
294                 frame = document.createElement('iframe'),
295                 hiddens = [],
296                 encoding = 'multipart/form-data',
297                 buf = {
298                     target: form.target,
299                     method: form.method,
300                     encoding: form.encoding,
301                     enctype: form.enctype,
302                     action: form.action
303                 }, hiddenItem;
304
305         /*
306          * Originally this behaviour was modified for Opera 10 to apply the secure URL after
307          * the frame had been added to the document. It seems this has since been corrected in
308          * Opera so the behaviour has been reverted, the URL will be set before being added.
309          */
310         Ext.fly(frame).set({
311             id: id,
312             name: id,
313             cls: Ext.baseCSSPrefix + 'hide-display',
314             src: Ext.SSL_SECURE_URL
315         });
316
317         document.body.appendChild(frame);
318
319         // This is required so that IE doesn't pop the response up in a new window.
320         if (document.frames) {
321            document.frames[id].name = id;
322         }
323
324         Ext.fly(form).set({
325             target: id,
326             method: 'POST',
327             enctype: encoding,
328             encoding: encoding,
329             action: url || buf.action
330         });
331
332         // add dynamic params
333         if (params) {
334             Ext.iterate(Ext.Object.fromQueryString(params), function(name, value){
335                 hiddenItem = document.createElement('input');
336                 Ext.fly(hiddenItem).set({
337                     type: 'hidden',
338                     value: value,
339                     name: name
340                 });
341                 form.appendChild(hiddenItem);
342                 hiddens.push(hiddenItem);
343             });
344         }
345
346         Ext.fly(frame).on('load', Ext.Function.bind(this.onUploadComplete, this, [frame, options]), null, {single: true});
347         form.submit();
348
349         Ext.fly(form).set(buf);
350         Ext.each(hiddens, function(h) {
351             Ext.removeNode(h);
352         });
353     },
354
355     onUploadComplete: function(frame, options){
356         var me = this,
357             // bogus response object
358             response = {
359                 responseText: '',
360                 responseXML: null
361             }, doc, firstChild;
362
363         try {
364             doc = frame.contentWindow.document || frame.contentDocument || window.frames[id].document;
365             if (doc) {
366                 if (doc.body) {
367                     if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
368                         response.responseText = firstChild.value;
369                     } else {
370                         response.responseText = doc.body.innerHTML;
371                     }
372                 }
373                 //in IE the document may still have a body even if returns XML.
374                 response.responseXML = doc.XMLDocument || doc;
375             }
376         } catch (e) {
377         }
378
379         me.fireEvent('requestcomplete', me, response, options);
380
381         Ext.callback(options.success, options.scope, [response, options]);
382         Ext.callback(options.callback, options.scope, [options, true, response]);
383
384         setTimeout(function(){
385             Ext.removeNode(frame);
386         }, 100);
387     },
388
389     /**
390      * Detect whether the form is intended to be used for an upload.
391      * @private
392      */
393     isFormUpload: function(options){
394         var form = this.getForm(options);
395         if (form) {
396             return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
397         }
398         return false;
399     },
400
401     /**
402      * Get the form object from options.
403      * @private
404      * @param {Object} options The request options
405      * @return {HTMLElement} The form, null if not passed
406      */
407     getForm: function(options){
408         return Ext.getDom(options.form) || null;
409     },
410
411     /**
412      * Set various options such as the url, params for the request
413      * @param {Object} options The initial options
414      * @param {Object} scope The scope to execute in
415      * @return {Object} The params for the request
416      */
417     setOptions: function(options, scope){
418         var me =  this,
419             params = options.params || {},
420             extraParams = me.extraParams,
421             urlParams = options.urlParams,
422             url = options.url || me.url,
423             jsonData = options.jsonData,
424             method,
425             disableCache,
426             data;
427
428
429         // allow params to be a method that returns the params object
430         if (Ext.isFunction(params)) {
431             params = params.call(scope, options);
432         }
433
434         // allow url to be a method that returns the actual url
435         if (Ext.isFunction(url)) {
436             url = url.call(scope, options);
437         }
438
439         url = this.setupUrl(options, url);
440
441         //<debug>
442         if (!url) {
443             Ext.Error.raise({
444                 options: options,
445                 msg: 'No URL specified'
446             });
447         }
448         //</debug>
449
450         // check for xml or json data, and make sure json data is encoded
451         data = options.rawData || options.xmlData || jsonData || null;
452         if (jsonData && !Ext.isPrimitive(jsonData)) {
453             data = Ext.encode(data);
454         }
455
456         // make sure params are a url encoded string and include any extraParams if specified
457         if (Ext.isObject(params)) {
458             params = Ext.Object.toQueryString(params);
459         }
460
461         if (Ext.isObject(extraParams)) {
462             extraParams = Ext.Object.toQueryString(extraParams);
463         }
464
465         params = params + ((extraParams) ? ((params) ? '&' : '') + extraParams : '');
466
467         urlParams = Ext.isObject(urlParams) ? Ext.Object.toQueryString(urlParams) : urlParams;
468
469         params = this.setupParams(options, params);
470
471         // decide the proper method for this request
472         method = (options.method || me.method || ((params || data) ? 'POST' : 'GET')).toUpperCase();
473         this.setupMethod(options, method);
474
475
476         disableCache = options.disableCaching !== false ? (options.disableCaching || me.disableCaching) : false;
477         // if the method is get append date to prevent caching
478         if (method === 'GET' && disableCache) {
479             url = Ext.urlAppend(url, (options.disableCachingParam || me.disableCachingParam) + '=' + (new Date().getTime()));
480         }
481
482         // if the method is get or there is json/xml data append the params to the url
483         if ((method == 'GET' || data) && params) {
484             url = Ext.urlAppend(url, params);
485             params = null;
486         }
487
488         // allow params to be forced into the url
489         if (urlParams) {
490             url = Ext.urlAppend(url, urlParams);
491         }
492
493         return {
494             url: url,
495             method: method,
496             data: data || params || null
497         };
498     },
499
500     /**
501      * Template method for overriding url
502      * @private
503      * @param {Object} options
504      * @param {String} url
505      * @return {String} The modified url
506      */
507     setupUrl: function(options, url){
508         var form = this.getForm(options);
509         if (form) {
510             url = url || form.action;
511         }
512         return url;
513     },
514
515
516     /**
517      * Template method for overriding params
518      * @private
519      * @param {Object} options
520      * @param {String} params
521      * @return {String} The modified params
522      */
523     setupParams: function(options, params) {
524         var form = this.getForm(options),
525             serializedForm;
526         if (form && !this.isFormUpload(options)) {
527             serializedForm = Ext.core.Element.serializeForm(form);
528             params = params ? (params + '&' + serializedForm) : serializedForm;
529         }
530         return params;
531     },
532
533     /**
534      * Template method for overriding method
535      * @private
536      * @param {Object} options
537      * @param {String} method
538      * @return {String} The modified method
539      */
540     setupMethod: function(options, method){
541         if (this.isFormUpload(options)) {
542             return 'POST';
543         }
544         return method;
545     },
546
547     /**
548      * Setup all the headers for the request
549      * @private
550      * @param {Object} xhr The xhr object
551      * @param {Object} options The options for the request
552      * @param {Object} data The data for the request
553      * @param {Object} params The params for the request
554      */
555     setupHeaders: function(xhr, options, data, params){
556         var me = this,
557             headers = Ext.apply({}, options.headers || {}, me.defaultHeaders || {}),
558             contentType = me.defaultPostHeader,
559             jsonData = options.jsonData,
560             xmlData = options.xmlData,
561             key,
562             header;
563
564         if (!headers['Content-Type'] && (data || params)) {
565             if (data) {
566                 if (options.rawData) {
567                     contentType = 'text/plain';
568                 } else {
569                     if (xmlData && Ext.isDefined(xmlData)) {
570                         contentType = 'text/xml';
571                     } else if (jsonData && Ext.isDefined(jsonData)) {
572                         contentType = 'application/json';
573                     }
574                 }
575             }
576             headers['Content-Type'] = contentType;
577         }
578
579         if (me.useDefaultXhrHeader && !headers['X-Requested-With']) {
580             headers['X-Requested-With'] = me.defaultXhrHeader;
581         }
582         // set up all the request headers on the xhr object
583         try{
584             for (key in headers) {
585                 if (headers.hasOwnProperty(key)) {
586                     header = headers[key];
587                     xhr.setRequestHeader(key, header);
588                 }
589
590             }
591         } catch(e) {
592             me.fireEvent('exception', key, header);
593         }
594         return headers;
595     },
596
597     /**
598      * Creates the appropriate XHR transport for the browser.
599      * @private
600      */
601     getXhrInstance: (function(){
602         var options = [function(){
603             return new XMLHttpRequest();
604         }, function(){
605             return new ActiveXObject('MSXML2.XMLHTTP.3.0');
606         }, function(){
607             return new ActiveXObject('MSXML2.XMLHTTP');
608         }, function(){
609             return new ActiveXObject('Microsoft.XMLHTTP');
610         }], i = 0,
611             len = options.length,
612             xhr;
613
614         for(; i < len; ++i) {
615             try{
616                 xhr = options[i];
617                 xhr();
618                 break;
619             }catch(e){}
620         }
621         return xhr;
622     })(),
623
624     /**
625      * Determine whether this object has a request outstanding.
626      * @param {Object} request (Optional) defaults to the last transaction
627      * @return {Boolean} True if there is an outstanding request.
628      */
629     isLoading : function(request) {
630         if (!(request && request.xhr)) {
631             return false;
632         }
633         // if there is a connection and readyState is not 0 or 4
634         var state = request.xhr.readyState;
635         return !(state === 0 || state == 4);
636     },
637
638     /**
639      * Aborts any outstanding request.
640      * @param {Object} request (Optional) defaults to the last request
641      */
642     abort : function(request) {
643         var me = this,
644             requests = me.requests,
645             id;
646
647         if (request && me.isLoading(request)) {
648             /**
649              * Clear out the onreadystatechange here, this allows us
650              * greater control, the browser may/may not fire the function
651              * depending on a series of conditions.
652              */
653             request.xhr.onreadystatechange = null;
654             request.xhr.abort();
655             me.clearTimeout(request);
656             if (!request.timedout) {
657                 request.aborted = true;
658             }
659             me.onComplete(request);
660             me.cleanup(request);
661         } else if (!request) {
662             for(id in requests) {
663                 if (requests.hasOwnProperty(id)) {
664                     me.abort(requests[id]);
665                 }
666             }
667         }
668     },
669
670     /**
671      * Fires when the state of the xhr changes
672      * @private
673      * @param {Object} request The request
674      */
675     onStateChange : function(request) {
676         if (request.xhr.readyState == 4) {
677             this.clearTimeout(request);
678             this.onComplete(request);
679             this.cleanup(request);
680         }
681     },
682
683     /**
684      * Clear the timeout on the request
685      * @private
686      * @param {Object} The request
687      */
688     clearTimeout: function(request){
689         clearTimeout(request.timeout);
690         delete request.timeout;
691     },
692
693     /**
694      * Clean up any left over information from the request
695      * @private
696      * @param {Object} The request
697      */
698     cleanup: function(request){
699         request.xhr = null;
700         delete request.xhr;
701     },
702
703     /**
704      * To be called when the request has come back from the server
705      * @private
706      * @param {Object} request
707      * @return {Object} The response
708      */
709     onComplete : function(request) {
710         var me = this,
711             options = request.options,
712             result = me.parseStatus(request.xhr.status),
713             success = result.success,
714             response;
715
716         if (success) {
717             response = me.createResponse(request);
718             me.fireEvent('requestcomplete', me, response, options);
719             Ext.callback(options.success, options.scope, [response, options]);
720         } else {
721             if (result.isException || request.aborted || request.timedout) {
722                 response = me.createException(request);
723             } else {
724                 response = me.createResponse(request);
725             }
726             me.fireEvent('requestexception', me, response, options);
727             Ext.callback(options.failure, options.scope, [response, options]);
728         }
729         Ext.callback(options.callback, options.scope, [options, success, response]);
730         delete me.requests[request.id];
731         return response;
732     },
733
734     /**
735      * Check if the response status was successful
736      * @param {Number} status The status code
737      * @return {Object} An object containing success/status state
738      */
739     parseStatus: function(status) {
740         // see: https://prototype.lighthouseapp.com/projects/8886/tickets/129-ie-mangles-http-response-status-code-204-to-1223
741         status = status == 1223 ? 204 : status;
742
743         var success = (status >= 200 && status < 300) || status == 304,
744             isException = false;
745
746         if (!success) {
747             switch (status) {
748                 case 12002:
749                 case 12029:
750                 case 12030:
751                 case 12031:
752                 case 12152:
753                 case 13030:
754                     isException = true;
755                     break;
756             }
757         }
758         return {
759             success: success,
760             isException: isException
761         };
762     },
763
764     /**
765      * Create the response object
766      * @private
767      * @param {Object} request
768      */
769     createResponse : function(request) {
770         var xhr = request.xhr,
771             headers = {},
772             lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'),
773             count = lines.length,
774             line, index, key, value, response;
775
776         while (count--) {
777             line = lines[count];
778             index = line.indexOf(':');
779             if(index >= 0) {
780                 key = line.substr(0, index).toLowerCase();
781                 if (line.charAt(index + 1) == ' ') {
782                     ++index;
783                 }
784                 headers[key] = line.substr(index + 1);
785             }
786         }
787
788         request.xhr = null;
789         delete request.xhr;
790
791         response = {
792             request: request,
793             requestId : request.id,
794             status : xhr.status,
795             statusText : xhr.statusText,
796             getResponseHeader : function(header){ return headers[header.toLowerCase()]; },
797             getAllResponseHeaders : function(){ return headers; },
798             responseText : xhr.responseText,
799             responseXML : xhr.responseXML
800         };
801
802         // If we don't explicitly tear down the xhr reference, IE6/IE7 will hold this in the closure of the
803         // functions created with getResponseHeader/getAllResponseHeaders
804         xhr = null;
805         return response;
806     },
807
808     /**
809      * Create the exception object
810      * @private
811      * @param {Object} request
812      */
813     createException : function(request) {
814         return {
815             request : request,
816             requestId : request.id,
817             status : request.aborted ? -1 : 0,
818             statusText : request.aborted ? 'transaction aborted' : 'communication failure',
819             aborted: request.aborted,
820             timedout: request.timedout
821         };
822     }
823 });