PageRenderTime 21ms CodeModel.GetById 12ms app.highlight 5ms RepoModel.GetById 0ms app.codeStats 0ms

/ext-4.1.0_b3/src/data/proxy/Ajax.js

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