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.
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 <form> element temporarily modified to have its
14 * target set to refer to a dynamically generated, hidden <iframe> 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 "<" as "&lt;", "&" as
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'
49 * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
54 * @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching
55 * through a cache buster. Defaults to '_dc'
57 disableCachingParam: '_dc',
60 * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
65 * @cfg {Object} extraParams (Optional) Any parameters to be appended to the request.
68 useDefaultHeader : true,
69 defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
70 useDefaultXhrHeader : true,
71 defaultXhrHeader : 'XMLHttpRequest',
73 constructor : function(config) {
74 config = config || {};
75 Ext.apply(this, config);
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.
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>
92 * @param {Object} options The options config object passed to the {@link #request} method.
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>
104 * @param {Object} options The options config object passed to the {@link #request} method.
109 this.mixins.observable.constructor.call(this);
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>
119 url: 'ajax_demo/sample.json',
120 success: function(response, opts) {
121 var obj = Ext.decode(response.responseText);
124 failure: function(response, opts) {
125 console.log('server-side failure with status code ' + response.status);
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
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>
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
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>
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>
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><form></tt>
171 * Element or the id of the <tt><form></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><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><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>
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>
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.
209 request : function(options) {
210 options = options || {};
212 scope = options.scope || window,
213 username = options.username || me.username,
214 password = options.password || me.password || '',
221 if (me.fireEvent('beforerequest', me, options) !== false) {
223 requestOptions = me.setOptions(options, scope);
225 if (this.isFormUpload(options) === true) {
226 this.upload(options.form, requestOptions.url, requestOptions.data, options);
230 // if autoabort is set, cancel the current transactions
231 if (options.autoAbort === true || me.autoAbort) {
235 // create a connection object
236 xhr = this.getXhrInstance();
238 async = options.async !== false ? (options.async || me.async) : false;
242 xhr.open(requestOptions.method, requestOptions.url, async, username, password);
244 xhr.open(requestOptions.method, requestOptions.url, async);
247 headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
249 // create the transaction object
251 id: ++Ext.data.Connection.requestId,
256 timeout: setTimeout(function() {
257 request.timedout = true;
259 }, options.timeout || me.timeout)
261 me.requests[request.id] = request;
263 // bind our statechange listener
265 xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
268 // start the request!
269 xhr.send(requestOptions.data);
271 return this.onComplete(request);
275 Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
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
287 upload: function(form, url, params, options){
288 form = Ext.getDom(form);
289 options = options || {};
292 frame = document.createElement('iframe'),
294 encoding = 'multipart/form-data',
298 encoding: form.encoding,
299 enctype: form.enctype,
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.
311 cls: Ext.baseCSSPrefix + 'hide-display',
312 src: Ext.SSL_SECURE_URL
315 document.body.appendChild(frame);
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;
327 action: url || buf.action
330 // add dynamic params
332 Ext.iterate(Ext.Object.fromQueryString(params), function(name, value){
333 hiddenItem = document.createElement('input');
334 Ext.fly(hiddenItem).set({
339 form.appendChild(hiddenItem);
340 hiddens.push(hiddenItem);
344 Ext.fly(frame).on('load', Ext.Function.bind(this.onUploadComplete, this, [frame, options]), null, {single: true});
347 Ext.fly(form).set(buf);
348 Ext.each(hiddens, function(h) {
353 onUploadComplete: function(frame, options){
355 // bogus response object
362 doc = frame.contentWindow.document || frame.contentDocument || window.frames[id].document;
365 if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
366 response.responseText = firstChild.value;
368 response.responseText = doc.body.innerHTML;
371 //in IE the document may still have a body even if returns XML.
372 response.responseXML = doc.XMLDocument || doc;
377 me.fireEvent('requestcomplete', me, response, options);
379 Ext.callback(options.success, options.scope, [response, options]);
380 Ext.callback(options.callback, options.scope, [options, true, response]);
382 setTimeout(function(){
383 Ext.removeNode(frame);
388 * Detect whether the form is intended to be used for an upload.
391 isFormUpload: function(options){
392 var form = this.getForm(options);
394 return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
400 * Get the form object from options.
402 * @param {Object} options The request options
403 * @return {HTMLElement} The form, null if not passed
405 getForm: function(options){
406 return Ext.getDom(options.form) || null;
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
415 setOptions: function(options, scope){
417 params = options.params || {},
418 extraParams = me.extraParams,
419 urlParams = options.urlParams,
420 url = options.url || me.url,
421 jsonData = options.jsonData,
427 // allow params to be a method that returns the params object
428 if (Ext.isFunction(params)) {
429 params = params.call(scope, options);
432 // allow url to be a method that returns the actual url
433 if (Ext.isFunction(url)) {
434 url = url.call(scope, options);
437 url = this.setupUrl(options, url);
443 msg: 'No URL specified'
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);
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);
459 if (Ext.isObject(extraParams)) {
460 extraParams = Ext.Object.toQueryString(extraParams);
463 params = params + ((extraParams) ? ((params) ? '&' : '') + extraParams : '');
465 urlParams = Ext.isObject(urlParams) ? Ext.Object.toQueryString(urlParams) : urlParams;
467 params = this.setupParams(options, params);
469 // decide the proper method for this request
470 method = (options.method || me.method || ((params || data) ? 'POST' : 'GET')).toUpperCase();
471 this.setupMethod(options, method);
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()));
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);
486 // allow params to be forced into the url
488 url = Ext.urlAppend(url, urlParams);
494 data: data || params || null
499 * Template method for overriding url
501 * @param {Object} options
502 * @param {String} url
503 * @return {String} The modified url
505 setupUrl: function(options, url){
506 var form = this.getForm(options);
508 url = url || form.action;
515 * Template method for overriding params
517 * @param {Object} options
518 * @param {String} params
519 * @return {String} The modified params
521 setupParams: function(options, params) {
522 var form = this.getForm(options),
524 if (form && !this.isFormUpload(options)) {
525 serializedForm = Ext.core.Element.serializeForm(form);
526 params = params ? (params + '&' + serializedForm) : serializedForm;
532 * Template method for overriding method
534 * @param {Object} options
535 * @param {String} method
536 * @return {String} The modified method
538 setupMethod: function(options, method){
539 if (this.isFormUpload(options)) {
546 * Setup all the headers for the request
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
553 setupHeaders: function(xhr, options, data, params){
555 headers = Ext.apply({}, options.headers || {}, me.defaultHeaders || {}),
556 contentType = me.defaultPostHeader,
557 jsonData = options.jsonData,
558 xmlData = options.xmlData,
562 if (!headers['Content-Type'] && (data || params)) {
564 if (options.rawData) {
565 contentType = 'text/plain';
567 if (xmlData && Ext.isDefined(xmlData)) {
568 contentType = 'text/xml';
569 } else if (jsonData && Ext.isDefined(jsonData)) {
570 contentType = 'application/json';
574 headers['Content-Type'] = contentType;
577 if (me.useDefaultXhrHeader && !headers['X-Requested-With']) {
578 headers['X-Requested-With'] = me.defaultXhrHeader;
580 // set up all the request headers on the xhr object
582 for (key in headers) {
583 if (headers.hasOwnProperty(key)) {
584 header = headers[key];
585 xhr.setRequestHeader(key, header);
590 me.fireEvent('exception', key, header);
596 * Creates the appropriate XHR transport for the browser.
599 getXhrInstance: (function(){
600 var options = [function(){
601 return new XMLHttpRequest();
603 return new ActiveXObject('MSXML2.XMLHTTP.3.0');
605 return new ActiveXObject('MSXML2.XMLHTTP');
607 return new ActiveXObject('Microsoft.XMLHTTP');
609 len = options.length,
612 for(; i < len; ++i) {
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.
627 isLoading : function(request) {
628 if (!(request && request.xhr)) {
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);
637 * Aborts any outstanding request.
638 * @param {Object} request (Optional) defaults to the last request
640 abort : function(request) {
642 requests = me.requests,
645 if (request && me.isLoading(request)) {
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.
651 request.xhr.onreadystatechange = null;
653 me.clearTimeout(request);
654 if (!request.timedout) {
655 request.aborted = true;
657 me.onComplete(request);
659 } else if (!request) {
660 for(id in requests) {
661 if (requests.hasOwnProperty(id)) {
662 me.abort(requests[id]);
669 * Fires when the state of the xhr changes
671 * @param {Object} request The request
673 onStateChange : function(request) {
674 if (request.xhr.readyState == 4) {
675 this.clearTimeout(request);
676 this.onComplete(request);
677 this.cleanup(request);
682 * Clear the timeout on the request
684 * @param {Object} The request
686 clearTimeout: function(request){
687 clearTimeout(request.timeout);
688 delete request.timeout;
692 * Clean up any left over information from the request
694 * @param {Object} The request
696 cleanup: function(request){
702 * To be called when the request has come back from the server
704 * @param {Object} request
705 * @return {Object} The response
707 onComplete : function(request) {
709 options = request.options,
710 result = me.parseStatus(request.xhr.status),
711 success = result.success,
715 response = me.createResponse(request);
716 me.fireEvent('requestcomplete', me, response, options);
717 Ext.callback(options.success, options.scope, [response, options]);
719 if (result.isException || request.aborted || request.timedout) {
720 response = me.createException(request);
722 response = me.createResponse(request);
724 me.fireEvent('requestexception', me, response, options);
725 Ext.callback(options.failure, options.scope, [response, options]);
727 Ext.callback(options.callback, options.scope, [options, success, response]);
728 delete me.requests[request.id];
733 * Check if the response status was successful
734 * @param {Number} status The status code
735 * @return {Object} An object containing success/status state
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;
741 var success = (status >= 200 && status < 300) || status == 304,
758 isException: isException
763 * Create the response object
765 * @param {Object} request
767 createResponse : function(request) {
768 var xhr = request.xhr,
770 lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'),
771 count = lines.length,
772 line, index, key, value, response;
776 index = line.indexOf(':');
778 key = line.substr(0, index).toLowerCase();
779 if (line.charAt(index + 1) == ' ') {
782 headers[key] = line.substr(index + 1);
791 requestId : request.id,
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
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
807 * Create the exception object
809 * @param {Object} request
811 createException : function(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