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