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