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; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
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.
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}.
27 * <p><u>File Uploads</u></p>
29 * File uploads are not performed using normal "Ajax" techniques, that is they are not performed using XMLHttpRequests.
30 * Instead the form is submitted in the standard manner with the DOM &lt;form&gt; element temporarily modified to have its
31 * target set to refer to a dynamically generated, hidden &lt;iframe&gt; which is inserted into the document but removed
32 * after the return data has been gathered.
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 "text/html" in order to tell the browser to
36 * insert the text unchanged into the document body.
38 * Characters which are significant to an HTML parser must be sent as HTML entities, so encode "&lt;" as "&amp;lt;", "&amp;" as
39 * "&amp;amp;" etc.
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.
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
48 * Also note that it's not possible to check the response code of the hidden iframe, so the success handler will ALWAYS fire.
50 Ext.define('Ext.data.Connection', {
52 observable: 'Ext.util.Observable'
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)
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'
74 disableCachingParam: '_dc',
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)
81 <span id='Ext-data-Connection-cfg-extraParams'> /**
82 </span> * @cfg {Object} extraParams (Optional) Any parameters to be appended to the request.
85 useDefaultHeader : true,
86 defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
87 useDefaultXhrHeader : true,
88 defaultXhrHeader : 'XMLHttpRequest',
90 constructor : function(config) {
91 config = config || {};
92 Ext.apply(this, config);
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.
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 <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
109 * @param {Object} options The options config object passed to the {@link #request} method.
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 <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Status Code Definitions</a>
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 <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
121 * @param {Object} options The options config object passed to the {@link #request} method.
126 this.mixins.observable.constructor.call(this);
129 <span id='Ext-data-Connection-method-request'> /**
130 </span> * <p>Sends an HTTP request to a remote server.</p>
131 * <p><b>Important:</b> 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.</p>
134 * <pre><code>
136 url: 'ajax_demo/sample.json',
137 success: function(response, opts) {
138 var obj = Ext.decode(response.responseText);
141 failure: function(response, opts) {
142 console.log('server-side failure with status code ' + response.status);
145 * </code></pre>
146 * <p>To execute a callback function in the correct scope, use the <tt>scope</tt> option.</p>
147 * @param {Object} options An object which may contain the following properties:<ul>
148 * <li><b>url</b> : String/Function (Optional)<div class="sub-desc">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 <tt>scope</tt> option. Defaults to the configured
151 * <tt>{@link #url}</tt>.</div></li>
152 * <li><b>params</b> : Object/String/Function (Optional)<div class="sub-desc">
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 <tt>scope</tt> option.</div></li>
156 * <li><b>method</b> : String (Optional)<div class="sub-desc">The HTTP method to use
157 * for the request. Defaults to the configured method, or if no method was configured,
158 * "GET" if no parameters are being sent, and "POST" if parameters are being sent. Note that
159 * the method name is case-sensitive and should be all caps.</div></li>
160 * <li><b>callback</b> : Function (Optional)<div class="sub-desc">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:<ul>
164 * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
165 * <li><b>success</b> : Boolean<div class="sub-desc">True if the request succeeded.</div></li>
166 * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.
167 * See <a href="http://www.w3.org/TR/XMLHttpRequest/">http://www.w3.org/TR/XMLHttpRequest/</a> for details about
168 * accessing elements of the response.</div></li>
169 * </ul></div></li>
170 * <li><a id="request-option-success"></a><b>success</b> : Function (Optional)<div class="sub-desc">The function
171 * to be called upon success of the request. The callback is passed the following
172 * parameters:<ul>
173 * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
174 * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
175 * </ul></div></li>
176 * <li><b>failure</b> : Function (Optional)<div class="sub-desc">The function
177 * to be called upon failure of the request. The callback is passed the
178 * following parameters:<ul>
179 * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
180 * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
181 * </ul></div></li>
182 * <li><b>scope</b> : Object (Optional)<div class="sub-desc">The scope in
183 * which to execute the callbacks: The "this" object for the callback function. If the <tt>url</tt>, or <tt>params</tt> 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.</div></li>
186 * <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>
187 * <li><b>form</b> : Element/HTMLElement/String (Optional)<div class="sub-desc">The <tt>&lt;form&gt;</tt>
188 * Element or the id of the <tt>&lt;form&gt;</tt> to pull parameters from.</div></li>
189 * <li><a id="request-option-isUpload"></a><b>isUpload</b> : Boolean (Optional)<div class="sub-desc"><b>Only meaningful when used
190 * with the <tt>form</tt> option</b>.
191 * <p>True if the form object is a file upload (will be set automatically if the form was
192 * configured with <b><tt>enctype</tt></b> "multipart/form-data").</p>
193 * <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
194 * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
195 * DOM <tt>&lt;form></tt> element temporarily modified to have its
196 * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
197 * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
198 * but removed after the return data has been gathered.</p>
199 * <p>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 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
202 * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
203 * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
204 * is created containing a <tt>responseText</tt> property in order to conform to the
205 * requirements of event handlers and callbacks.</p>
206 * <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>
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.</p>
209 * </div></li>
210 * <li><b>headers</b> : Object (Optional)<div class="sub-desc">Request
211 * headers to set for the request.</div></li>
212 * <li><b>xmlData</b> : Object (Optional)<div class="sub-desc">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.</div></li>
215 * <li><b>jsonData</b> : Object/String (Optional)<div class="sub-desc">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.</div></li>
218 * <li><b>disableCaching</b> : Boolean (Optional)<div class="sub-desc">True
219 * to add a unique cache-buster param to GET requests.</div></li>
220 * </ul></p>
221 * <p>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.</p>
223 * @return {Object} request The request object. This may be used
224 * to cancel the request.
226 request : function(options) {
227 options = options || {};
229 scope = options.scope || window,
230 username = options.username || me.username,
231 password = options.password || me.password || '',
238 if (me.fireEvent('beforerequest', me, options) !== false) {
240 requestOptions = me.setOptions(options, scope);
242 if (this.isFormUpload(options) === true) {
243 this.upload(options.form, requestOptions.url, requestOptions.data, options);
247 // if autoabort is set, cancel the current transactions
248 if (options.autoAbort === true || me.autoAbort) {
252 // create a connection object
253 xhr = this.getXhrInstance();
255 async = options.async !== false ? (options.async || me.async) : false;
259 xhr.open(requestOptions.method, requestOptions.url, async, username, password);
261 xhr.open(requestOptions.method, requestOptions.url, async);
264 headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
266 // create the transaction object
268 id: ++Ext.data.Connection.requestId,
273 timeout: setTimeout(function() {
274 request.timedout = true;
276 }, options.timeout || me.timeout)
278 me.requests[request.id] = request;
280 // bind our statechange listener
282 xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
285 // start the request!
286 xhr.send(requestOptions.data);
288 return this.onComplete(request);
292 Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
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
304 upload: function(form, url, params, options){
305 form = Ext.getDom(form);
306 options = options || {};
309 frame = document.createElement('iframe'),
311 encoding = 'multipart/form-data',
315 encoding: form.encoding,
316 enctype: form.enctype,
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.
328 cls: Ext.baseCSSPrefix + 'hide-display',
329 src: Ext.SSL_SECURE_URL
332 document.body.appendChild(frame);
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;
344 action: url || buf.action
347 // add dynamic params
349 Ext.iterate(Ext.Object.fromQueryString(params), function(name, value){
350 hiddenItem = document.createElement('input');
351 Ext.fly(hiddenItem).set({
356 form.appendChild(hiddenItem);
357 hiddens.push(hiddenItem);
361 Ext.fly(frame).on('load', Ext.Function.bind(this.onUploadComplete, this, [frame, options]), null, {single: true});
364 Ext.fly(form).set(buf);
365 Ext.each(hiddens, function(h) {
370 onUploadComplete: function(frame, options){
372 // bogus response object
379 doc = frame.contentWindow.document || frame.contentDocument || window.frames[id].document;
382 if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
383 response.responseText = firstChild.value;
385 response.responseText = doc.body.innerHTML;
388 //in IE the document may still have a body even if returns XML.
389 response.responseXML = doc.XMLDocument || doc;
394 me.fireEvent('requestcomplete', me, response, options);
396 Ext.callback(options.success, options.scope, [response, options]);
397 Ext.callback(options.callback, options.scope, [options, true, response]);
399 setTimeout(function(){
400 Ext.removeNode(frame);
404 <span id='Ext-data-Connection-method-isFormUpload'> /**
405 </span> * Detect whether the form is intended to be used for an upload.
408 isFormUpload: function(options){
409 var form = this.getForm(options);
411 return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
416 <span id='Ext-data-Connection-method-getForm'> /**
417 </span> * Get the form object from options.
419 * @param {Object} options The request options
420 * @return {HTMLElement} The form, null if not passed
422 getForm: function(options){
423 return Ext.getDom(options.form) || null;
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
432 setOptions: function(options, scope){
434 params = options.params || {},
435 extraParams = me.extraParams,
436 urlParams = options.urlParams,
437 url = options.url || me.url,
438 jsonData = options.jsonData,
444 // allow params to be a method that returns the params object
445 if (Ext.isFunction(params)) {
446 params = params.call(scope, options);
449 // allow url to be a method that returns the actual url
450 if (Ext.isFunction(url)) {
451 url = url.call(scope, options);
454 url = this.setupUrl(options, url);
460 msg: 'No URL specified'
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 && !Ext.isPrimitive(jsonData)) {
468 data = Ext.encode(data);
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);
476 if (Ext.isObject(extraParams)) {
477 extraParams = Ext.Object.toQueryString(extraParams);
480 params = params + ((extraParams) ? ((params) ? '&' : '') + extraParams : '');
482 urlParams = Ext.isObject(urlParams) ? Ext.Object.toQueryString(urlParams) : urlParams;
484 params = this.setupParams(options, params);
486 // decide the proper method for this request
487 method = (options.method || me.method || ((params || data) ? 'POST' : 'GET')).toUpperCase();
488 this.setupMethod(options, method);
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' && disableCache) {
494 url = Ext.urlAppend(url, (options.disableCachingParam || me.disableCachingParam) + '=' + (new Date().getTime()));
497 // if the method is get or there is json/xml data append the params to the url
498 if ((method == 'GET' || data) && params) {
499 url = Ext.urlAppend(url, params);
503 // allow params to be forced into the url
505 url = Ext.urlAppend(url, urlParams);
511 data: data || params || null
515 <span id='Ext-data-Connection-method-setupUrl'> /**
516 </span> * Template method for overriding url
518 * @param {Object} options
519 * @param {String} url
520 * @return {String} The modified url
522 setupUrl: function(options, url){
523 var form = this.getForm(options);
525 url = url || form.action;
531 <span id='Ext-data-Connection-method-setupParams'> /**
532 </span> * Template method for overriding params
534 * @param {Object} options
535 * @param {String} params
536 * @return {String} The modified params
538 setupParams: function(options, params) {
539 var form = this.getForm(options),
541 if (form && !this.isFormUpload(options)) {
542 serializedForm = Ext.core.Element.serializeForm(form);
543 params = params ? (params + '&' + serializedForm) : serializedForm;
548 <span id='Ext-data-Connection-method-setupMethod'> /**
549 </span> * Template method for overriding method
551 * @param {Object} options
552 * @param {String} method
553 * @return {String} The modified method
555 setupMethod: function(options, method){
556 if (this.isFormUpload(options)) {
562 <span id='Ext-data-Connection-method-setupHeaders'> /**
563 </span> * Setup all the headers for the request
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
570 setupHeaders: function(xhr, options, data, params){
572 headers = Ext.apply({}, options.headers || {}, me.defaultHeaders || {}),
573 contentType = me.defaultPostHeader,
574 jsonData = options.jsonData,
575 xmlData = options.xmlData,
579 if (!headers['Content-Type'] && (data || params)) {
581 if (options.rawData) {
582 contentType = 'text/plain';
584 if (xmlData && Ext.isDefined(xmlData)) {
585 contentType = 'text/xml';
586 } else if (jsonData && Ext.isDefined(jsonData)) {
587 contentType = 'application/json';
591 headers['Content-Type'] = contentType;
594 if (me.useDefaultXhrHeader && !headers['X-Requested-With']) {
595 headers['X-Requested-With'] = me.defaultXhrHeader;
597 // set up all the request headers on the xhr object
599 for (key in headers) {
600 if (headers.hasOwnProperty(key)) {
601 header = headers[key];
602 xhr.setRequestHeader(key, header);
607 me.fireEvent('exception', key, header);
612 <span id='Ext-data-Connection-property-getXhrInstance'> /**
613 </span> * Creates the appropriate XHR transport for the browser.
616 getXhrInstance: (function(){
617 var options = [function(){
618 return new XMLHttpRequest();
620 return new ActiveXObject('MSXML2.XMLHTTP.3.0');
622 return new ActiveXObject('MSXML2.XMLHTTP');
624 return new ActiveXObject('Microsoft.XMLHTTP');
626 len = options.length,
629 for(; i < len; ++i) {
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.
644 isLoading : function(request) {
645 if (!(request && request.xhr)) {
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);
653 <span id='Ext-data-Connection-method-abort'> /**
654 </span> * Aborts any outstanding request.
655 * @param {Object} request (Optional) defaults to the last request
657 abort : function(request) {
659 requests = me.requests,
662 if (request && me.isLoading(request)) {
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.
668 request.xhr.onreadystatechange = null;
670 me.clearTimeout(request);
671 if (!request.timedout) {
672 request.aborted = true;
674 me.onComplete(request);
676 } else if (!request) {
677 for(id in requests) {
678 if (requests.hasOwnProperty(id)) {
679 me.abort(requests[id]);
685 <span id='Ext-data-Connection-method-onStateChange'> /**
686 </span> * Fires when the state of the xhr changes
688 * @param {Object} request The request
690 onStateChange : function(request) {
691 if (request.xhr.readyState == 4) {
692 this.clearTimeout(request);
693 this.onComplete(request);
694 this.cleanup(request);
698 <span id='Ext-data-Connection-method-clearTimeout'> /**
699 </span> * Clear the timeout on the request
701 * @param {Object} The request
703 clearTimeout: function(request){
704 clearTimeout(request.timeout);
705 delete request.timeout;
708 <span id='Ext-data-Connection-method-cleanup'> /**
709 </span> * Clean up any left over information from the request
711 * @param {Object} The request
713 cleanup: function(request){
718 <span id='Ext-data-Connection-method-onComplete'> /**
719 </span> * To be called when the request has come back from the server
721 * @param {Object} request
722 * @return {Object} The response
724 onComplete : function(request) {
726 options = request.options,
727 result = me.parseStatus(request.xhr.status),
728 success = result.success,
732 response = me.createResponse(request);
733 me.fireEvent('requestcomplete', me, response, options);
734 Ext.callback(options.success, options.scope, [response, options]);
736 if (result.isException || request.aborted || request.timedout) {
737 response = me.createException(request);
739 response = me.createResponse(request);
741 me.fireEvent('requestexception', me, response, options);
742 Ext.callback(options.failure, options.scope, [response, options]);
744 Ext.callback(options.callback, options.scope, [options, success, response]);
745 delete me.requests[request.id];
749 <span id='Ext-data-Connection-method-parseStatus'> /**
750 </span> * Check if the response status was successful
751 * @param {Number} status The status code
752 * @return {Object} An object containing success/status state
754 parseStatus: function(status) {
755 // see: https://prototype.lighthouseapp.com/projects/8886/tickets/129-ie-mangles-http-response-status-code-204-to-1223
756 status = status == 1223 ? 204 : status;
758 var success = (status >= 200 && status < 300) || status == 304,
775 isException: isException
779 <span id='Ext-data-Connection-method-createResponse'> /**
780 </span> * Create the response object
782 * @param {Object} request
784 createResponse : function(request) {
785 var xhr = request.xhr,
787 lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'),
788 count = lines.length,
789 line, index, key, value, response;
793 index = line.indexOf(':');
795 key = line.substr(0, index).toLowerCase();
796 if (line.charAt(index + 1) == ' ') {
799 headers[key] = line.substr(index + 1);
808 requestId : request.id,
810 statusText : xhr.statusText,
811 getResponseHeader : function(header){ return headers[header.toLowerCase()]; },
812 getAllResponseHeaders : function(){ return headers; },
813 responseText : xhr.responseText,
814 responseXML : xhr.responseXML
817 // If we don't explicitly tear down the xhr reference, IE6/IE7 will hold this in the closure of the
818 // functions created with getResponseHeader/getAllResponseHeaders
823 <span id='Ext-data-Connection-method-createException'> /**
824 </span> * Create the exception object
826 * @param {Object} request
828 createException : function(request) {
831 requestId : request.id,
832 status : request.aborted ? -1 : 0,
833 statusText : request.aborted ? 'transaction aborted' : 'communication failure',
834 aborted: request.aborted,
835 timedout: request.timedout