/** * @class Ext.data.Connection * @extends Ext.util.Observable */ Ext.data.Connection = Ext.extend(Ext.util.Observable, { method: 'post', url: null,
/** * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true) * @type Boolean */ disableCaching: true,
/** * @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching * through a cache buster. Defaults to '_dc' * @type String */ disableCachingParam: '_dc',
/** * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000) */ timeout : 30000, useDefaultHeader : true, defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8', useDefaultXhrHeader : true, defaultXhrHeader : 'XMLHttpRequest', constructor : function(config) { config = config || {}; Ext.apply(this, config); this.addEvents(
/** * @event beforerequest * Fires before a network request is made to retrieve a data object. * @param {Connection} conn This Connection object. * @param {Object} options The options config object passed to the {@link #request} method. */ 'beforerequest',
/** * @event requestcomplete * Fires if the request was successfully completed. * @param {Connection} conn This Connection object. * @param {Object} response The XHR object containing the response data. * See The XMLHttpRequest Object * for details. * @param {Object} options The options config object passed to the {@link #request} method. */ 'requestcomplete',
/** * @event requestexception * Fires if an error HTTP status was returned from the server. * See HTTP Status Code Definitions * for details of HTTP status codes. * @param {Connection} conn This Connection object. * @param {Object} response The XHR object containing the response data. * See The XMLHttpRequest Object * for details. * @param {Object} options The options config object passed to the {@link #request} method. */ 'requestexception' ); this.requests = {}; Ext.data.Connection.superclass.constructor.call(this); },
/** *

Sends an HTTP request to a remote server.

*

Important: Ajax server requests are asynchronous, and this call will * return before the response has been received. Process any returned data * in a callback function.

*

Ext.Ajax.request({
url: 'ajax_demo/sample.json',
success: function(response, opts) {
  var obj = Ext.decode(response.responseText);
  console.dir(obj);
},
failure: function(response, opts) {
  console.log('server-side failure with status code ' + response.status);
}
});
     * 
*

To execute a callback function in the correct scope, use the scope option.

* @param {Object} options An object which may contain the following properties:

*

The options object may also contain any other property which might be needed to perform * postprocessing in a callback because it is passed to callback functions.

* @return {Object} request The request object. This may be used * to cancel the request. */ request : function(o) { var me = this; if (me.fireEvent('beforerequest', me, o) !== false) { var params = o.params, url = o.url || me.url, urlParams = o.urlParams, extraParams = me.extraParams, request, data, headers, method, key, xhr; // allow params to be a method that returns the params object if (Ext.isFunction(params)) { params = params.call(o.scope || window, o); } // allow url to be a method that returns the actual url if (Ext.isFunction(url)) { url = url.call(o.scope || window, o); } // check for xml or json data, and make sure json data is encoded data = o.rawData || o.xmlData || o.jsonData || null; if (o.jsonData && !Ext.isPrimitive(o.jsonData)) { data = Ext.encode(data); } // make sure params are a url encoded string and include any extraParams if specified params = Ext.urlEncode(extraParams, Ext.isObject(params) ? Ext.urlEncode(params) : params); urlParams = Ext.isObject(urlParams) ? Ext.urlEncode(urlParams) : urlParams; // decide the proper method for this request method = (o.method || ((params || data) ? 'POST' : 'GET')).toUpperCase(); // if the method is get append date to prevent caching if (method === 'GET' && o.disableCaching !== false && me.disableCaching) { url = Ext.urlAppend(url, o.disableCachingParam || me.disableCachingParam + '=' + (new Date().getTime())); } // if the method is get or there is json/xml data append the params to the url if ((method == 'GET' || data) && params){ url = Ext.urlAppend(url, params); params = null; } // allow params to be forced into the url if (urlParams) { url = Ext.urlAppend(url, urlParams); } // if autoabort is set, cancel the current transactions if (o.autoAbort === true || me.autoAbort) { me.abort(); } // create a connection object xhr = this.getXhrInstance(); // open the request xhr.open(method.toUpperCase(), url, true); // create all the headers headers = Ext.apply({}, o.headers || {}, me.defaultHeaders || {}); if (!headers['Content-Type'] && (data || params)) { var contentType = me.defaultPostHeader, jsonData = o.jsonData, xmlData = o.xmlData; if (data) { if (o.rawData) { contentType = 'text/plain'; } else { if (xmlData && Ext.isDefined(xmlData)) { contentType = 'text/xml'; } else if (jsonData && Ext.isDefined(jsonData)) { contentType = 'application/json'; } } } headers['Content-Type'] = contentType; } if (me.useDefaultXhrHeader && !headers['X-Requested-With']) { headers['X-Requested-With'] = me.defaultXhrHeader; } // set up all the request headers on the xhr object for (key in headers) { if (headers.hasOwnProperty(key)) { try { xhr.setRequestHeader(key, headers[key]); } catch(e) { me.fireEvent('exception', key, headers[key]); } } } // create the transaction object request = { id: ++Ext.data.Connection.requestId, xhr: xhr, headers: headers, options: o, timeout: setTimeout(function() { request.timedout = true; me.abort(request); }, o.timeout || me.timeout) }; me.requests[request.id] = request; // bind our statechange listener xhr.onreadystatechange = Ext.createDelegate(me.onStateChange, me, [request]); // start the request! xhr.send(data || params || null); return request; } else { return o.callback ? o.callback.apply(o.scope, [o, undefined, undefined]) : null; } }, getXhrInstance : function() { return new XMLHttpRequest(); },
/** * Determine whether this object has a request outstanding. * @param {Object} request (Optional) defaults to the last transaction * @return {Boolean} True if there is an outstanding request. */ isLoading : function(r) { // if there is a connection and readyState is not 0 or 4 return r && !{0:true, 4:true}[r.xhr.readyState]; },
/** * Aborts any outstanding request. * @param {Object} request (Optional) defaults to the last request */ abort : function(r) { if (r && this.isLoading(r)) { r.xhr.abort(); clearTimeout(r.timeout); delete(r.timeout); r.aborted = true; this.onComplete(r); } else if (!r) { var id; for(id in this.requests) { if (!this.requests.hasOwnProperty(id)) { continue; } this.abort(this.requests[id]); } } }, // private onStateChange : function(r) { if (r.xhr.readyState == 4) { clearTimeout(r.timeout); delete r.timeout; this.onComplete(r); } }, // private onComplete : function(r) { var status = r.xhr.status, options = r.options, success = true, response; if ((status >= 200 && status < 300) || status == 304) { response = this.createResponse(r); this.fireEvent('requestcomplete', this, response, options); if (options.success) { if (!options.scope) { options.success(response, options); } else { options.success.call(options.scope, response, options); } } } else { success = false; switch (status) { case 12002: case 12029: case 12030: case 12031: case 12152: case 13030: response = this.createException(r); break; default: response = this.createResponse(r); } this.fireEvent('requestexception', this, response, options); if (options.failure) { if (!options.scope) { options.failure(response, options); } else { options.failure.call(options.scope, response, options); } } } if (options.callback) { if (!options.scope) { options.callback(options, success, response); } else { options.callback.call(options.scope, options, success, response); } } delete this.requests[r.id]; }, // private createResponse : function(r) { var xhr = r.xhr, headers = {}, lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'), count = lines.length, line, index, key, value; while (count--) { line = lines[count]; index = line.indexOf(':'); if(index >= 0) { key = line.substr(0, index).toLowerCase(); if (line.charAt(index + 1) == ' ') { ++index; } headers[key] = line.substr(index + 1); } } delete r.xhr; return { request: r, requestId : r.id, status : xhr.status, statusText : xhr.statusText, getResponseHeader : function(header){ return headers[header.toLowerCase()]; }, getAllResponseHeaders : function(){ return headers; }, responseText : xhr.responseText, responseXML : xhr.responseXML }; }, // private createException : function(r) { return { request : r, requestId : r.id, status : r.aborted ? -1 : 0, statusText : r.aborted ? 'transaction aborted' : 'communication failure', aborted: r.aborted, timedout: r.timedout }; } }); Ext.data.Connection.requestId = 0;
/** * @class Ext.Ajax * @extends Ext.data.Connection * A singleton instance of an {@link Ext.data.Connection}. * @singleton */ Ext.Ajax = new Ext.data.Connection({
/** * @cfg {String} url @hide */
/** * @cfg {Object} extraParams @hide */
/** * @cfg {Object} defaultHeaders @hide */
/** * @cfg {String} method (Optional) @hide */
/** * @cfg {Number} timeout (Optional) @hide */
/** * @cfg {Boolean} autoAbort (Optional) @hide */
/** * @cfg {Boolean} disableCaching (Optional) @hide */
/** * @property disableCaching * True to add a unique cache-buster param to GET requests. (defaults to true) * @type Boolean */
/** * @property url * The default URL to be used for requests to the server. (defaults to undefined) * If the server receives all requests through one URL, setting this once is easier than * entering it on every request. * @type String */
/** * @property extraParams * An object containing properties which are used as extra parameters to each request made * by this object (defaults to undefined). Session information and other data that you need * to pass with each request are commonly put here. * @type Object */
/** * @property defaultHeaders * An object containing request headers which are added to each request made by this object * (defaults to undefined). * @type Object */
/** * @property method * The default HTTP method to be used for requests. Note that this is case-sensitive and * should be all caps (defaults to undefined; if not set but params are present will use * "POST", otherwise will use "GET".) * @type String */
/** * @property timeout * The timeout in milliseconds to be used for requests. (defaults to 30000) * @type Number */
/** * @property autoAbort * Whether a new request should abort any pending requests. (defaults to false) * @type Boolean */ autoAbort : false });