Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / docs / source / Ajax.html
index 97a8de7..788f558 100644 (file)
   </script>
 </head>
 <body onload="prettyPrint(); highlight();">
-  <pre class="prettyprint lang-js"><span id='Ext-Ajax'>/**
-</span> * @class Ext.Ajax
- * @singleton
- * @markdown
- * @extends Ext.data.Connection
+  <pre class="prettyprint lang-js"><span id='Ext-data-proxy-Ajax-method-constructor'><span id='Ext-data-proxy-Ajax'>/**
+</span></span> * @author Ed Spencer
+ * @class Ext.data.proxy.Ajax
+ * @extends Ext.data.proxy.Server
+ * 
+ * &lt;p&gt;AjaxProxy is one of the most widely-used ways of getting data into your application. It uses AJAX requests to 
+ * load data from the server, usually to be placed into a {@link Ext.data.Store Store}. Let's take a look at a typical
+ * setup. Here we're going to set up a Store that has an AjaxProxy. To prepare, we'll also set up a 
+ * {@link Ext.data.Model Model}:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+Ext.define('User', {
+    extend: 'Ext.data.Model',
+    fields: ['id', 'name', 'email']
+});
 
-A singleton instance of an {@link Ext.data.Connection}. This class
-is used to communicate with your server side code. It can be used as follows:
+//The Store contains the AjaxProxy as an inline configuration
+var store = new Ext.data.Store({
+    model: 'User',
+    proxy: {
+        type: 'ajax',
+        url : 'users.json'
+    }
+});
 
-    Ext.Ajax.request({
-        url: 'page.php',
-        params: {
-            id: 1
-        },
-        success: function(response){
-            var text = response.responseText;
-            // process server response here
-        }
-    });
+store.load();
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;Our example is going to load user data into a Store, so we start off by defining a {@link Ext.data.Model Model}
+ * with the fields that we expect the server to return. Next we set up the Store itself, along with a {@link #proxy}
+ * configuration. This configuration was automatically turned into an Ext.data.proxy.Ajax instance, with the url we
+ * specified being passed into AjaxProxy's constructor. It's as if we'd done this:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+new Ext.data.proxy.Ajax({
+    url: 'users.json',
+    model: 'User',
+    reader: 'json'
+});
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;A couple of extra configurations appeared here - {@link #model} and {@link #reader}. These are set by default 
+ * when we create the proxy via the Store - the Store already knows about the Model, and Proxy's default 
+ * {@link Ext.data.reader.Reader Reader} is {@link Ext.data.reader.Json JsonReader}.&lt;/p&gt;
+ * 
+ * &lt;p&gt;Now when we call store.load(), the AjaxProxy springs into action, making a request to the url we configured
+ * ('users.json' in this case). As we're performing a read, it sends a GET request to that url (see {@link #actionMethods}
+ * to customize this - by default any kind of read will be sent as a GET request and any kind of write will be sent as a
+ * POST request).&lt;/p&gt;
+ * 
+ * &lt;p&gt;&lt;u&gt;Limitations&lt;/u&gt;&lt;/p&gt;
+ * 
+ * &lt;p&gt;AjaxProxy cannot be used to retrieve data from other domains. If your application is running on http://domainA.com
+ * it cannot load data from http://domainB.com because browsers have a built-in security policy that prohibits domains
+ * talking to each other via AJAX.&lt;/p&gt;
+ * 
+ * &lt;p&gt;If you need to read data from another domain and can't set up a proxy server (some software that runs on your own
+ * domain's web server and transparently forwards requests to http://domainB.com, making it look like they actually came
+ * from http://domainA.com), you can use {@link Ext.data.proxy.JsonP} and a technique known as JSON-P (JSON with 
+ * Padding), which can help you get around the problem so long as the server on http://domainB.com is set up to support
+ * JSON-P responses. See {@link Ext.data.proxy.JsonP JsonPProxy}'s introduction docs for more details.&lt;/p&gt;
+ * 
+ * &lt;p&gt;&lt;u&gt;Readers and Writers&lt;/u&gt;&lt;/p&gt;
+ * 
+ * &lt;p&gt;AjaxProxy can be configured to use any type of {@link Ext.data.reader.Reader Reader} to decode the server's response. If
+ * no Reader is supplied, AjaxProxy will default to using a {@link Ext.data.reader.Json JsonReader}. Reader configuration
+ * can be passed in as a simple object, which the Proxy automatically turns into a {@link Ext.data.reader.Reader Reader}
+ * instance:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+var proxy = new Ext.data.proxy.Ajax({
+    model: 'User',
+    reader: {
+        type: 'xml',
+        root: 'users'
+    }
+});
 
-Default options for all requests can be set by changing a property on the Ext.Ajax class:
+proxy.getReader(); //returns an {@link Ext.data.reader.Xml XmlReader} instance based on the config we supplied
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;&lt;u&gt;Url generation&lt;/u&gt;&lt;/p&gt;
+ * 
+ * &lt;p&gt;AjaxProxy automatically inserts any sorting, filtering, paging and grouping options into the url it generates for
+ * each request. These are controlled with the following configuration options:&lt;/p&gt;
+ * 
+ * &lt;ul style=&quot;list-style-type: disc; padding-left: 20px;&quot;&gt;
+ *     &lt;li&gt;{@link #pageParam} - controls how the page number is sent to the server 
+ *     (see also {@link #startParam} and {@link #limitParam})&lt;/li&gt;
+ *     &lt;li&gt;{@link #sortParam} - controls how sort information is sent to the server&lt;/li&gt;
+ *     &lt;li&gt;{@link #groupParam} - controls how grouping information is sent to the server&lt;/li&gt;
+ *     &lt;li&gt;{@link #filterParam} - controls how filter information is sent to the server&lt;/li&gt;
+ * &lt;/ul&gt;
+ * 
+ * &lt;p&gt;Each request sent by AjaxProxy is described by an {@link Ext.data.Operation Operation}. To see how we can 
+ * customize the generated urls, let's say we're loading the Proxy with the following Operation:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+var operation = new Ext.data.Operation({
+    action: 'read',
+    page  : 2
+});
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;Now we'll issue the request for this Operation by calling {@link #read}:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+var proxy = new Ext.data.proxy.Ajax({
+    url: '/users'
+});
 
-    Ext.Ajax.timeout = 60000; // 60 seconds
+proxy.read(operation); //GET /users?page=2
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;Easy enough - the Proxy just copied the page property from the Operation. We can customize how this page data is
+ * sent to the server:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+var proxy = new Ext.data.proxy.Ajax({
+    url: '/users',
+    pagePage: 'pageNumber'
+});
 
-Any options specified in the request method for the Ajax request will override any
-defaults set on the Ext.Ajax class. In the code sample below, the timeout for the
-request will be 60 seconds.
+proxy.read(operation); //GET /users?pageNumber=2
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;Alternatively, our Operation could have been configured to send start and limit parameters instead of page:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+var operation = new Ext.data.Operation({
+    action: 'read',
+    start : 50,
+    limit : 25
+});
 
-    Ext.Ajax.timeout = 120000; // 120 seconds
-    Ext.Ajax.request({
-        url: 'page.aspx',
-        timeout: 60000
-    });
+var proxy = new Ext.data.proxy.Ajax({
+    url: '/users'
+});
 
-In general, this class will be used for all Ajax requests in your application.
-The main reason for creating a separate {@link Ext.data.Connection} is for a
-series of requests that share common settings that are different to all other
-requests in the application.
+proxy.read(operation); //GET /users?start=50&amp;limit=25
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;Again we can customize this url:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+var proxy = new Ext.data.proxy.Ajax({
+    url: '/users',
+    startParam: 'startIndex',
+    limitParam: 'limitIndex'
+});
 
- */
-Ext.define('Ext.Ajax', {
-    extend: 'Ext.data.Connection',
-    singleton: true,
+proxy.read(operation); //GET /users?startIndex=50&amp;limitIndex=25
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;AjaxProxy will also send sort and filter information to the server. Let's take a look at how this looks with a
+ * more expressive Operation object:&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+var operation = new Ext.data.Operation({
+    action: 'read',
+    sorters: [
+        new Ext.util.Sorter({
+            property : 'name',
+            direction: 'ASC'
+        }),
+        new Ext.util.Sorter({
+            property : 'age',
+            direction: 'DESC'
+        })
+    ],
+    filters: [
+        new Ext.util.Filter({
+            property: 'eyeColor',
+            value   : 'brown'
+        })
+    ]
+});
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;This is the type of object that is generated internally when loading a {@link Ext.data.Store Store} with sorters
+ * and filters defined. By default the AjaxProxy will JSON encode the sorters and filters, resulting in something like
+ * this (note that the url is escaped before sending the request, but is left unescaped here for clarity):&lt;/p&gt;
+ * 
+&lt;pre&gt;&lt;code&gt;
+var proxy = new Ext.data.proxy.Ajax({
+    url: '/users'
+});
 
-<span id='Ext-Ajax-cfg-url'>    /**
-</span>     * @cfg {String} url @hide
-     */
-<span id='Ext-Ajax-cfg-extraParams'>    /**
-</span>     * @cfg {Object} extraParams @hide
-     */
-<span id='Ext-Ajax-cfg-defaultHeaders'>    /**
-</span>     * @cfg {Object} defaultHeaders @hide
-     */
-<span id='Ext-Ajax-cfg-method'>    /**
-</span>     * @cfg {String} method (Optional) @hide
-     */
-<span id='Ext-Ajax-cfg-timeout'>    /**
-</span>     * @cfg {Number} timeout (Optional) @hide
-     */
-<span id='Ext-Ajax-cfg-autoAbort'>    /**
-</span>     * @cfg {Boolean} autoAbort (Optional) @hide
-     */
+proxy.read(operation); //GET /users?sort=[{&quot;property&quot;:&quot;name&quot;,&quot;direction&quot;:&quot;ASC&quot;},{&quot;property&quot;:&quot;age&quot;,&quot;direction&quot;:&quot;DESC&quot;}]&amp;filter=[{&quot;property&quot;:&quot;eyeColor&quot;,&quot;value&quot;:&quot;brown&quot;}]
+&lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;We can again customize how this is created by supplying a few configuration options. Let's say our server is set 
+ * up to receive sorting information is a format like &quot;sortBy=name#ASC,age#DESC&quot;. We can configure AjaxProxy to provide
+ * that format like this:&lt;/p&gt;
+ * 
+ &lt;pre&gt;&lt;code&gt;
+ var proxy = new Ext.data.proxy.Ajax({
+     url: '/users',
+     sortParam: 'sortBy',
+     filterParam: 'filterBy',
 
-<span id='Ext-Ajax-cfg-disableCaching'>    /**
-</span>     * @cfg {Boolean} disableCaching (Optional) @hide
-     */
+     //our custom implementation of sorter encoding - turns our sorters into &quot;name#ASC,age#DESC&quot;
+     encodeSorters: function(sorters) {
+         var length   = sorters.length,
+             sortStrs = [],
+             sorter, i;
 
-<span id='Ext-Ajax-property-disableCaching'>    /**
-</span>     * @property  disableCaching
-     * True to add a unique cache-buster param to GET requests. (defaults to true)
-     * @type Boolean
-     */
-<span id='Ext-Ajax-property-url'>    /**
-</span>     * @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
-     */
-<span id='Ext-Ajax-property-extraParams'>    /**
-</span>     * @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
+         for (i = 0; i &lt; length; i++) {
+             sorter = sorters[i];
+
+             sortStrs[i] = sorter.property + '#' + sorter.direction
+         }
+
+         return sortStrs.join(&quot;,&quot;);
+     }
+ });
+
+ proxy.read(operation); //GET /users?sortBy=name#ASC,age#DESC&amp;filterBy=[{&quot;property&quot;:&quot;eyeColor&quot;,&quot;value&quot;:&quot;brown&quot;}]
+ &lt;/code&gt;&lt;/pre&gt;
+ * 
+ * &lt;p&gt;We can also provide a custom {@link #encodeFilters} function to encode our filters.&lt;/p&gt;
+ * 
+ * @constructor
+ * 
+ * &lt;p&gt;Note that if this HttpProxy is being used by a {@link Ext.data.Store Store}, then the
+ * Store's call to {@link #load} will override any specified &lt;tt&gt;callback&lt;/tt&gt; and &lt;tt&gt;params&lt;/tt&gt;
+ * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,
+ * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be
+ * used to pass parameters known at instantiation time.&lt;/p&gt;
+ * 
+ * &lt;p&gt;If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make
+ * the request.&lt;/p&gt;
+ */
+Ext.define('Ext.data.proxy.Ajax', {
+    requires: ['Ext.util.MixedCollection', 'Ext.Ajax'],
+    extend: 'Ext.data.proxy.Server',
+    alias: 'proxy.ajax',
+    alternateClassName: ['Ext.data.HttpProxy', 'Ext.data.AjaxProxy'],
+    
+<span id='Ext-data-proxy-Ajax-property-actionMethods'>    /**
+</span>     * @property actionMethods
+     * Mapping of action name to HTTP request method. In the basic AjaxProxy these are set to 'GET' for 'read' actions and 'POST' 
+     * for 'create', 'update' and 'destroy' actions. The {@link Ext.data.proxy.Rest} maps these to the correct RESTful methods.
      */
-<span id='Ext-Ajax-property-defaultHeaders'>    /**
-</span>     * @property  defaultHeaders
-     * An object containing request headers which are added to each request made by this object
-     * (defaults to undefined).
-     * @type Object
+    actionMethods: {
+        create : 'POST',
+        read   : 'GET',
+        update : 'POST',
+        destroy: 'POST'
+    },
+    
+<span id='Ext-data-proxy-Ajax-cfg-headers'>    /**
+</span>     * @cfg {Object} headers Any headers to add to the Ajax request. Defaults to &lt;tt&gt;undefined&lt;/tt&gt;.
      */
-<span id='Ext-Ajax-property-method'>    /**
-</span>     * @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
-     * &lt;tt&gt;&quot;POST&quot;&lt;/tt&gt;, otherwise will use &lt;tt&gt;&quot;GET&quot;&lt;/tt&gt;.)
-     * @type String
+    
+<span id='Ext-data-proxy-Ajax-method-doRequest'>    /**
+</span>     * @ignore
      */
-<span id='Ext-Ajax-property-timeout'>    /**
-</span>     * @property  timeout
-     * The timeout in milliseconds to be used for requests. (defaults to 30000)
-     * @type Number
+    doRequest: function(operation, callback, scope) {
+        var writer  = this.getWriter(),
+            request = this.buildRequest(operation, callback, scope);
+            
+        if (operation.allowWrite()) {
+            request = writer.write(request);
+        }
+        
+        Ext.apply(request, {
+            headers       : this.headers,
+            timeout       : this.timeout,
+            scope         : this,
+            callback      : this.createRequestCallback(request, operation, callback, scope),
+            method        : this.getMethod(request),
+            disableCaching: false // explicitly set it to false, ServerProxy handles caching
+        });
+        
+        Ext.Ajax.request(request);
+        
+        return request;
+    },
+    
+<span id='Ext-data-proxy-Ajax-method-getMethod'>    /**
+</span>     * Returns the HTTP method name for a given request. By default this returns based on a lookup on {@link #actionMethods}.
+     * @param {Ext.data.Request} request The request object
+     * @return {String} The HTTP method to use (should be one of 'GET', 'POST', 'PUT' or 'DELETE')
      */
-
-<span id='Ext-Ajax-property-autoAbort'>    /**
-</span>     * @property  autoAbort
-     * Whether a new request should abort any pending requests. (defaults to false)
-     * @type Boolean
+    getMethod: function(request) {
+        return this.actionMethods[request.action];
+    },
+    
+<span id='Ext-data-proxy-Ajax-method-createRequestCallback'>    /**
+</span>     * @private
+     * TODO: This is currently identical to the JsonPProxy version except for the return function's signature. There is a lot
+     * of code duplication inside the returned function so we need to find a way to DRY this up.
+     * @param {Ext.data.Request} request The Request object
+     * @param {Ext.data.Operation} operation The Operation being executed
+     * @param {Function} callback The callback function to be called when the request completes. This is usually the callback
+     * passed to doRequest
+     * @param {Object} scope The scope in which to execute the callback function
+     * @return {Function} The callback function
      */
-    autoAbort : false
-});</pre>
+    createRequestCallback: function(request, operation, callback, scope) {
+        var me = this;
+        
+        return function(options, success, response) {
+            me.processResponse(success, operation, request, response, callback, scope);
+        };
+    }
+}, function() {
+    //backwards compatibility, remove in Ext JS 5.0
+    Ext.data.HttpProxy = this;
+});
+</pre>
 </body>
 </html>