1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-data.Connection'>/**
2 </span> * @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.
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}.
10 * <p><u>File Uploads</u></p>
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.
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.
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.
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.
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
31 * Also note that it's not possible to check the response code of the hidden iframe, so the success handler will ALWAYS fire.
33 Ext.define('Ext.data.Connection', {
35 observable: 'Ext.util.Observable'
48 <span id='Ext-data.Connection-property-disableCaching'> /**
49 </span> * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
54 <span id='Ext-data.Connection-property-disableCachingParam'> /**
55 </span> * @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching
56 * through a cache buster. Defaults to '_dc'
59 disableCachingParam: '_dc',
61 <span id='Ext-data.Connection-cfg-timeout'> /**
62 </span> * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
66 <span id='Ext-data.Connection-property-useDefaultHeader'> /**
67 </span> * @param {Object} extraParams (Optional) Any parameters to be appended to the request.
70 useDefaultHeader : true,
71 defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
72 useDefaultXhrHeader : true,
73 defaultXhrHeader : 'XMLHttpRequest',
75 constructor : function(config) {
76 config = config || {};
77 Ext.apply(this, config);
80 <span id='Ext-data.Connection-event-beforerequest'> /**
81 </span> * @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.
87 <span id='Ext-data.Connection-event-requestcomplete'> /**
88 </span> * @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>
94 * @param {Object} options The options config object passed to the {@link #request} method.
97 <span id='Ext-data.Connection-event-requestexception'> /**
98 </span> * @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>
106 * @param {Object} options The options config object passed to the {@link #request} method.
111 this.mixins.observable.constructor.call(this);
114 <span id='Ext-data.Connection-method-request'> /**
115 </span> * <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>
121 url: 'ajax_demo/sample.json',
122 success: function(response, opts) {
123 var obj = Ext.decode(response.responseText);
126 failure: function(response, opts) {
127 console.log('server-side failure with status code ' + response.status);
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.
211 request : function(options) {
212 options = options || {};
214 scope = options.scope || window,
215 username = options.username || me.username,
216 password = options.password || me.password || '',
223 if (me.fireEvent('beforerequest', me, options) !== false) {
225 requestOptions = me.setOptions(options, scope);
227 if (this.isFormUpload(options) === true) {
228 this.upload(options.form, requestOptions.url, requestOptions.data, options);
232 // if autoabort is set, cancel the current transactions
233 if (options.autoAbort === true || me.autoAbort) {
237 // create a connection object
238 xhr = this.getXhrInstance();
240 async = options.async !== false ? (options.async || me.async) : false;
244 xhr.open(requestOptions.method, requestOptions.url, async, username, password);
246 xhr.open(requestOptions.method, requestOptions.url, async);
249 headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
251 // create the transaction object
253 id: ++Ext.data.Connection.requestId,
258 timeout: setTimeout(function() {
259 request.timedout = true;
261 }, options.timeout || me.timeout)
263 me.requests[request.id] = request;
265 // bind our statechange listener
267 xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
270 // start the request!
271 xhr.send(requestOptions.data);
273 return this.onComplete(request);
277 Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
282 <span id='Ext-data.Connection-method-upload'> /**
283 </span> * 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
289 upload: function(form, url, params, options){
290 form = Ext.getDom(form);
291 options = options || {};
294 frame = document.createElement('iframe'),
296 encoding = 'multipart/form-data',
300 encoding: form.encoding,
301 enctype: form.enctype,
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.
313 cls: Ext.baseCSSPrefix + 'hide-display',
314 src: Ext.SSL_SECURE_URL
317 document.body.appendChild(frame);
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;
329 action: url || buf.action
332 // add dynamic params
334 Ext.iterate(Ext.Object.fromQueryString(params), function(name, value){
335 hiddenItem = document.createElement('input');
336 Ext.fly(hiddenItem).set({
341 form.appendChild(hiddenItem);
342 hiddens.push(hiddenItem);
346 Ext.fly(frame).on('load', Ext.Function.bind(this.onUploadComplete, this, [frame, options]), null, {single: true});
349 Ext.fly(form).set(buf);
350 Ext.each(hiddens, function(h) {
355 onUploadComplete: function(frame, options){
357 // bogus response object
364 doc = frame.contentWindow.document || frame.contentDocument || window.frames[id].document;
367 if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
368 response.responseText = firstChild.value;
370 response.responseText = doc.body.innerHTML;
373 //in IE the document may still have a body even if returns XML.
374 response.responseXML = doc.XMLDocument || doc;
379 me.fireEvent('requestcomplete', me, response, options);
381 Ext.callback(options.success, options.scope, [response, options]);
382 Ext.callback(options.callback, options.scope, [options, true, response]);
384 setTimeout(function(){
385 Ext.removeNode(frame);
389 <span id='Ext-data.Connection-method-isFormUpload'> /**
390 </span> * Detect whether the form is intended to be used for an upload.
393 isFormUpload: function(options){
394 var form = this.getForm(options);
396 return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
401 <span id='Ext-data.Connection-method-getForm'> /**
402 </span> * Get the form object from options.
404 * @param {Object} options The request options
405 * @return {HTMLElement} The form, null if not passed
407 getForm: function(options){
408 return Ext.getDom(options.form) || null;
411 <span id='Ext-data.Connection-method-setOptions'> /**
412 </span> * 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
417 setOptions: function(options, scope){
419 params = options.params || {},
420 extraParams = me.extraParams,
421 urlParams = options.urlParams,
422 url = options.url || me.url,
423 jsonData = options.jsonData,
429 // allow params to be a method that returns the params object
430 if (Ext.isFunction(params)) {
431 params = params.call(scope, options);
434 // allow url to be a method that returns the actual url
435 if (Ext.isFunction(url)) {
436 url = url.call(scope, options);
439 url = this.setupUrl(options, url);
445 msg: 'No URL specified'
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);
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);
461 if (Ext.isObject(extraParams)) {
462 extraParams = Ext.Object.toQueryString(extraParams);
465 params = params + ((extraParams) ? ((params) ? '&' : '') + extraParams : '');
467 urlParams = Ext.isObject(urlParams) ? Ext.Object.toQueryString(urlParams) : urlParams;
469 params = this.setupParams(options, params);
471 // decide the proper method for this request
472 method = (options.method || me.method || ((params || data) ? 'POST' : 'GET')).toUpperCase();
473 this.setupMethod(options, method);
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()));
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);
488 // allow params to be forced into the url
490 url = Ext.urlAppend(url, urlParams);
496 data: data || params || null
500 <span id='Ext-data.Connection-method-setupUrl'> /**
501 </span> * Template method for overriding url
503 * @param {Object} options
504 * @param {String} url
505 * @return {String} The modified url
507 setupUrl: function(options, url){
508 var form = this.getForm(options);
510 url = url || form.action;
516 <span id='Ext-data.Connection-method-setupParams'> /**
517 </span> * Template method for overriding params
519 * @param {Object} options
520 * @param {String} params
521 * @return {String} The modified params
523 setupParams: function(options, params) {
524 var form = this.getForm(options),
526 if (form && !this.isFormUpload(options)) {
527 serializedForm = Ext.core.Element.serializeForm(form);
528 params = params ? (params + '&' + serializedForm) : serializedForm;
533 <span id='Ext-data.Connection-method-setupMethod'> /**
534 </span> * Template method for overriding method
536 * @param {Object} options
537 * @param {String} method
538 * @return {String} The modified method
540 setupMethod: function(options, method){
541 if (this.isFormUpload(options)) {
547 <span id='Ext-data.Connection-method-setupHeaders'> /**
548 </span> * Setup all the headers for the request
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
555 setupHeaders: function(xhr, options, data, params){
557 headers = Ext.apply({}, options.headers || {}, me.defaultHeaders || {}),
558 contentType = me.defaultPostHeader,
559 jsonData = options.jsonData,
560 xmlData = options.xmlData,
564 if (!headers['Content-Type'] && (data || params)) {
566 if (options.rawData) {
567 contentType = 'text/plain';
569 if (xmlData && Ext.isDefined(xmlData)) {
570 contentType = 'text/xml';
571 } else if (jsonData && Ext.isDefined(jsonData)) {
572 contentType = 'application/json';
576 headers['Content-Type'] = contentType;
579 if (me.useDefaultXhrHeader && !headers['X-Requested-With']) {
580 headers['X-Requested-With'] = me.defaultXhrHeader;
582 // set up all the request headers on the xhr object
584 for (key in headers) {
585 if (headers.hasOwnProperty(key)) {
586 header = headers[key];
587 xhr.setRequestHeader(key, header);
592 me.fireEvent('exception', key, header);
597 <span id='Ext-data.Connection-property-getXhrInstance'> /**
598 </span> * Creates the appropriate XHR transport for the browser.
601 getXhrInstance: (function(){
602 var options = [function(){
603 return new XMLHttpRequest();
605 return new ActiveXObject('MSXML2.XMLHTTP.3.0');
607 return new ActiveXObject('MSXML2.XMLHTTP');
609 return new ActiveXObject('Microsoft.XMLHTTP');
611 len = options.length,
614 for(; i < len; ++i) {
624 <span id='Ext-data.Connection-method-isLoading'> /**
625 </span> * 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.
629 isLoading : function(request) {
630 if (!(request && request.xhr)) {
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);
638 <span id='Ext-data.Connection-method-abort'> /**
639 </span> * Aborts any outstanding request.
640 * @param {Object} request (Optional) defaults to the last request
642 abort : function(request) {
644 requests = me.requests,
647 if (request && me.isLoading(request)) {
648 <span id='Ext-data.Connection-property-onreadystatechange'> /**
649 </span> * 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.
653 request.xhr.onreadystatechange = null;
655 me.clearTimeout(request);
656 if (!request.timedout) {
657 request.aborted = true;
659 me.onComplete(request);
661 } else if (!request) {
662 for(id in requests) {
663 if (requests.hasOwnProperty(id)) {
664 me.abort(requests[id]);
670 <span id='Ext-data.Connection-method-onStateChange'> /**
671 </span> * Fires when the state of the xhr changes
673 * @param {Object} request The request
675 onStateChange : function(request) {
676 if (request.xhr.readyState == 4) {
677 this.clearTimeout(request);
678 this.onComplete(request);
679 this.cleanup(request);
683 <span id='Ext-data.Connection-method-clearTimeout'> /**
684 </span> * Clear the timeout on the request
686 * @param {Object} The request
688 clearTimeout: function(request){
689 clearTimeout(request.timeout);
690 delete request.timeout;
693 <span id='Ext-data.Connection-method-cleanup'> /**
694 </span> * Clean up any left over information from the request
696 * @param {Object} The request
698 cleanup: function(request){
703 <span id='Ext-data.Connection-method-onComplete'> /**
704 </span> * To be called when the request has come back from the server
706 * @param {Object} request
707 * @return {Object} The response
709 onComplete : function(request) {
711 options = request.options,
712 result = me.parseStatus(request.xhr.status),
713 success = result.success,
717 response = me.createResponse(request);
718 me.fireEvent('requestcomplete', me, response, options);
719 Ext.callback(options.success, options.scope, [response, options]);
721 if (result.isException || request.aborted || request.timedout) {
722 response = me.createException(request);
724 response = me.createResponse(request);
726 me.fireEvent('requestexception', me, response, options);
727 Ext.callback(options.failure, options.scope, [response, options]);
729 Ext.callback(options.callback, options.scope, [options, success, response]);
730 delete me.requests[request.id];
734 <span id='Ext-data.Connection-method-parseStatus'> /**
735 </span> * Check if the response status was successful
736 * @param {Number} status The status code
737 * @return {Object} An object containing success/status state
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;
743 var success = (status >= 200 && status < 300) || status == 304,
760 isException: isException
764 <span id='Ext-data.Connection-method-createResponse'> /**
765 </span> * Create the response object
767 * @param {Object} request
769 createResponse : function(request) {
770 var xhr = request.xhr,
772 lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'),
773 count = lines.length,
774 line, index, key, value, response;
778 index = line.indexOf(':');
780 key = line.substr(0, index).toLowerCase();
781 if (line.charAt(index + 1) == ' ') {
784 headers[key] = line.substr(index + 1);
793 requestId : request.id,
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
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
808 <span id='Ext-data.Connection-method-createException'> /**
809 </span> * Create the exception object
811 * @param {Object} request
813 createException : function(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
824 </pre></pre></body></html>