Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / docs / source / Ajax2.html
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.proxy.Ajax-method-constructor'><span id='Ext-data.proxy.Ajax'>/**
2 </span></span> * @author Ed Spencer
3  * @class Ext.data.proxy.Ajax
4  * @extends Ext.data.proxy.Server
5  * 
6  * &lt;p&gt;AjaxProxy is one of the most widely-used ways of getting data into your application. It uses AJAX requests to 
7  * load data from the server, usually to be placed into a {@link Ext.data.Store Store}. Let's take a look at a typical
8  * setup. Here we're going to set up a Store that has an AjaxProxy. To prepare, we'll also set up a 
9  * {@link Ext.data.Model Model}:&lt;/p&gt;
10  * 
11 &lt;pre&gt;&lt;code&gt;
12 Ext.define('User', {
13     extend: 'Ext.data.Model',
14     fields: ['id', 'name', 'email']
15 });
16
17 //The Store contains the AjaxProxy as an inline configuration
18 var store = new Ext.data.Store({
19     model: 'User',
20     proxy: {
21         type: 'ajax',
22         url : 'users.json'
23     }
24 });
25
26 store.load();
27 &lt;/code&gt;&lt;/pre&gt;
28  * 
29  * &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}
30  * with the fields that we expect the server to return. Next we set up the Store itself, along with a {@link #proxy}
31  * configuration. This configuration was automatically turned into an Ext.data.proxy.Ajax instance, with the url we
32  * specified being passed into AjaxProxy's constructor. It's as if we'd done this:&lt;/p&gt;
33  * 
34 &lt;pre&gt;&lt;code&gt;
35 new Ext.data.proxy.Ajax({
36     url: 'users.json',
37     model: 'User',
38     reader: 'json'
39 });
40 &lt;/code&gt;&lt;/pre&gt;
41  * 
42  * &lt;p&gt;A couple of extra configurations appeared here - {@link #model} and {@link #reader}. These are set by default 
43  * when we create the proxy via the Store - the Store already knows about the Model, and Proxy's default 
44  * {@link Ext.data.reader.Reader Reader} is {@link Ext.data.reader.Json JsonReader}.&lt;/p&gt;
45  * 
46  * &lt;p&gt;Now when we call store.load(), the AjaxProxy springs into action, making a request to the url we configured
47  * ('users.json' in this case). As we're performing a read, it sends a GET request to that url (see {@link #actionMethods}
48  * 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
49  * POST request).&lt;/p&gt;
50  * 
51  * &lt;p&gt;&lt;u&gt;Limitations&lt;/u&gt;&lt;/p&gt;
52  * 
53  * &lt;p&gt;AjaxProxy cannot be used to retrieve data from other domains. If your application is running on http://domainA.com
54  * it cannot load data from http://domainB.com because browsers have a built-in security policy that prohibits domains
55  * talking to each other via AJAX.&lt;/p&gt;
56  * 
57  * &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
58  * domain's web server and transparently forwards requests to http://domainB.com, making it look like they actually came
59  * from http://domainA.com), you can use {@link Ext.data.proxy.JsonP} and a technique known as JSON-P (JSON with 
60  * Padding), which can help you get around the problem so long as the server on http://domainB.com is set up to support
61  * JSON-P responses. See {@link Ext.data.proxy.JsonP JsonPProxy}'s introduction docs for more details.&lt;/p&gt;
62  * 
63  * &lt;p&gt;&lt;u&gt;Readers and Writers&lt;/u&gt;&lt;/p&gt;
64  * 
65  * &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
66  * no Reader is supplied, AjaxProxy will default to using a {@link Ext.data.reader.Json JsonReader}. Reader configuration
67  * can be passed in as a simple object, which the Proxy automatically turns into a {@link Ext.data.reader.Reader Reader}
68  * instance:&lt;/p&gt;
69  * 
70 &lt;pre&gt;&lt;code&gt;
71 var proxy = new Ext.data.proxy.Ajax({
72     model: 'User',
73     reader: {
74         type: 'xml',
75         root: 'users'
76     }
77 });
78
79 proxy.getReader(); //returns an {@link Ext.data.reader.Xml XmlReader} instance based on the config we supplied
80 &lt;/code&gt;&lt;/pre&gt;
81  * 
82  * &lt;p&gt;&lt;u&gt;Url generation&lt;/u&gt;&lt;/p&gt;
83  * 
84  * &lt;p&gt;AjaxProxy automatically inserts any sorting, filtering, paging and grouping options into the url it generates for
85  * each request. These are controlled with the following configuration options:&lt;/p&gt;
86  * 
87  * &lt;ul style=&quot;list-style-type: disc; padding-left: 20px;&quot;&gt;
88  *     &lt;li&gt;{@link #pageParam} - controls how the page number is sent to the server 
89  *     (see also {@link #startParam} and {@link #limitParam})&lt;/li&gt;
90  *     &lt;li&gt;{@link #sortParam} - controls how sort information is sent to the server&lt;/li&gt;
91  *     &lt;li&gt;{@link #groupParam} - controls how grouping information is sent to the server&lt;/li&gt;
92  *     &lt;li&gt;{@link #filterParam} - controls how filter information is sent to the server&lt;/li&gt;
93  * &lt;/ul&gt;
94  * 
95  * &lt;p&gt;Each request sent by AjaxProxy is described by an {@link Ext.data.Operation Operation}. To see how we can 
96  * customize the generated urls, let's say we're loading the Proxy with the following Operation:&lt;/p&gt;
97  * 
98 &lt;pre&gt;&lt;code&gt;
99 var operation = new Ext.data.Operation({
100     action: 'read',
101     page  : 2
102 });
103 &lt;/code&gt;&lt;/pre&gt;
104  * 
105  * &lt;p&gt;Now we'll issue the request for this Operation by calling {@link #read}:&lt;/p&gt;
106  * 
107 &lt;pre&gt;&lt;code&gt;
108 var proxy = new Ext.data.proxy.Ajax({
109     url: '/users'
110 });
111
112 proxy.read(operation); //GET /users?page=2
113 &lt;/code&gt;&lt;/pre&gt;
114  * 
115  * &lt;p&gt;Easy enough - the Proxy just copied the page property from the Operation. We can customize how this page data is
116  * sent to the server:&lt;/p&gt;
117  * 
118 &lt;pre&gt;&lt;code&gt;
119 var proxy = new Ext.data.proxy.Ajax({
120     url: '/users',
121     pagePage: 'pageNumber'
122 });
123
124 proxy.read(operation); //GET /users?pageNumber=2
125 &lt;/code&gt;&lt;/pre&gt;
126  * 
127  * &lt;p&gt;Alternatively, our Operation could have been configured to send start and limit parameters instead of page:&lt;/p&gt;
128  * 
129 &lt;pre&gt;&lt;code&gt;
130 var operation = new Ext.data.Operation({
131     action: 'read',
132     start : 50,
133     limit : 25
134 });
135
136 var proxy = new Ext.data.proxy.Ajax({
137     url: '/users'
138 });
139
140 proxy.read(operation); //GET /users?start=50&amp;limit=25
141 &lt;/code&gt;&lt;/pre&gt;
142  * 
143  * &lt;p&gt;Again we can customize this url:&lt;/p&gt;
144  * 
145 &lt;pre&gt;&lt;code&gt;
146 var proxy = new Ext.data.proxy.Ajax({
147     url: '/users',
148     startParam: 'startIndex',
149     limitParam: 'limitIndex'
150 });
151
152 proxy.read(operation); //GET /users?startIndex=50&amp;limitIndex=25
153 &lt;/code&gt;&lt;/pre&gt;
154  * 
155  * &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
156  * more expressive Operation object:&lt;/p&gt;
157  * 
158 &lt;pre&gt;&lt;code&gt;
159 var operation = new Ext.data.Operation({
160     action: 'read',
161     sorters: [
162         new Ext.util.Sorter({
163             property : 'name',
164             direction: 'ASC'
165         }),
166         new Ext.util.Sorter({
167             property : 'age',
168             direction: 'DESC'
169         })
170     ],
171     filters: [
172         new Ext.util.Filter({
173             property: 'eyeColor',
174             value   : 'brown'
175         })
176     ]
177 });
178 &lt;/code&gt;&lt;/pre&gt;
179  * 
180  * &lt;p&gt;This is the type of object that is generated internally when loading a {@link Ext.data.Store Store} with sorters
181  * and filters defined. By default the AjaxProxy will JSON encode the sorters and filters, resulting in something like
182  * this (note that the url is escaped before sending the request, but is left unescaped here for clarity):&lt;/p&gt;
183  * 
184 &lt;pre&gt;&lt;code&gt;
185 var proxy = new Ext.data.proxy.Ajax({
186     url: '/users'
187 });
188
189 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;}]
190 &lt;/code&gt;&lt;/pre&gt;
191  * 
192  * &lt;p&gt;We can again customize how this is created by supplying a few configuration options. Let's say our server is set 
193  * up to receive sorting information is a format like &quot;sortBy=name#ASC,age#DESC&quot;. We can configure AjaxProxy to provide
194  * that format like this:&lt;/p&gt;
195  * 
196  &lt;pre&gt;&lt;code&gt;
197  var proxy = new Ext.data.proxy.Ajax({
198      url: '/users',
199      sortParam: 'sortBy',
200      filterParam: 'filterBy',
201
202      //our custom implementation of sorter encoding - turns our sorters into &quot;name#ASC,age#DESC&quot;
203      encodeSorters: function(sorters) {
204          var length   = sorters.length,
205              sortStrs = [],
206              sorter, i;
207
208          for (i = 0; i &lt; length; i++) {
209              sorter = sorters[i];
210
211              sortStrs[i] = sorter.property + '#' + sorter.direction
212          }
213
214          return sortStrs.join(&quot;,&quot;);
215      }
216  });
217
218  proxy.read(operation); //GET /users?sortBy=name#ASC,age#DESC&amp;filterBy=[{&quot;property&quot;:&quot;eyeColor&quot;,&quot;value&quot;:&quot;brown&quot;}]
219  &lt;/code&gt;&lt;/pre&gt;
220  * 
221  * &lt;p&gt;We can also provide a custom {@link #encodeFilters} function to encode our filters.&lt;/p&gt;
222  * 
223  * @constructor
224  * 
225  * &lt;p&gt;Note that if this HttpProxy is being used by a {@link Ext.data.Store Store}, then the
226  * 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;
227  * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,
228  * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be
229  * used to pass parameters known at instantiation time.&lt;/p&gt;
230  * 
231  * &lt;p&gt;If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make
232  * the request.&lt;/p&gt;
233  */
234 Ext.define('Ext.data.proxy.Ajax', {
235     requires: ['Ext.util.MixedCollection', 'Ext.Ajax'],
236     extend: 'Ext.data.proxy.Server',
237     alias: 'proxy.ajax',
238     alternateClassName: ['Ext.data.HttpProxy', 'Ext.data.AjaxProxy'],
239     
240 <span id='Ext-data.proxy.Ajax-property-actionMethods'>    /**
241 </span>     * @property actionMethods
242      * Mapping of action name to HTTP request method. In the basic AjaxProxy these are set to 'GET' for 'read' actions and 'POST' 
243      * for 'create', 'update' and 'destroy' actions. The {@link Ext.data.proxy.Rest} maps these to the correct RESTful methods.
244      */
245     actionMethods: {
246         create : 'POST',
247         read   : 'GET',
248         update : 'POST',
249         destroy: 'POST'
250     },
251     
252 <span id='Ext-data.proxy.Ajax-cfg-headers'>    /**
253 </span>     * @cfg {Object} headers Any headers to add to the Ajax request. Defaults to &lt;tt&gt;undefined&lt;/tt&gt;.
254      */
255     
256 <span id='Ext-data.proxy.Ajax-method-doRequest'>    /**
257 </span>     * @ignore
258      */
259     doRequest: function(operation, callback, scope) {
260         var writer  = this.getWriter(),
261             request = this.buildRequest(operation, callback, scope);
262             
263         if (operation.allowWrite()) {
264             request = writer.write(request);
265         }
266         
267         Ext.apply(request, {
268             headers       : this.headers,
269             timeout       : this.timeout,
270             scope         : this,
271             callback      : this.createRequestCallback(request, operation, callback, scope),
272             method        : this.getMethod(request),
273             disableCaching: false // explicitly set it to false, ServerProxy handles caching
274         });
275         
276         Ext.Ajax.request(request);
277         
278         return request;
279     },
280     
281 <span id='Ext-data.proxy.Ajax-method-getMethod'>    /**
282 </span>     * Returns the HTTP method name for a given request. By default this returns based on a lookup on {@link #actionMethods}.
283      * @param {Ext.data.Request} request The request object
284      * @return {String} The HTTP method to use (should be one of 'GET', 'POST', 'PUT' or 'DELETE')
285      */
286     getMethod: function(request) {
287         return this.actionMethods[request.action];
288     },
289     
290 <span id='Ext-data.proxy.Ajax-method-createRequestCallback'>    /**
291 </span>     * @private
292      * TODO: This is currently identical to the JsonPProxy version except for the return function's signature. There is a lot
293      * of code duplication inside the returned function so we need to find a way to DRY this up.
294      * @param {Ext.data.Request} request The Request object
295      * @param {Ext.data.Operation} operation The Operation being executed
296      * @param {Function} callback The callback function to be called when the request completes. This is usually the callback
297      * passed to doRequest
298      * @param {Object} scope The scope in which to execute the callback function
299      * @return {Function} The callback function
300      */
301     createRequestCallback: function(request, operation, callback, scope) {
302         var me = this;
303         
304         return function(options, success, response) {
305             me.processResponse(success, operation, request, response, callback, scope);
306         };
307     }
308 }, function() {
309     //backwards compatibility, remove in Ext JS 5.0
310     Ext.data.HttpProxy = this;
311 });
312 </pre></pre></body></html>