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