ExtJs4 Learning (8) Data Proxy, extjs4proxy

Source: Internet
Author: User

ExtJs4 Learning (8) Data Proxy, extjs4proxy

ExtJs data proxy we will introduce four common types, but will focus on ajax proxy, because this is the most commonly used in daily development.

Ext. data. proxy. Ajax

AjaxProxy (Ajax data proxy class) is the most widely used method to obtain data in your applications. it uses AJAX requests to obtain data from the server, and then usually puts them into the Store. let's look at a typical configuration. here we set up an AjaxProxy proxy for a Store. first, we have prepared a Model:

Ext. define ('user', {extend: 'ext. data. model ', fields: ['id', 'name', 'email']}); // a Store containing the AjaxProxy proxy, which is bound using parameters. var store = Ext. create ('ext. data. store', {model: 'user', proxy: {type: 'ajax ', url: 'users. json '}); store. load (); store. each (function (record) {console.info (record. get ('name '));});

In our example, the user data will be loaded into the Store. First, we define a Model. The field (fields) contained in the Model is the corresponding field of the data returned from the server. next, we define a Store that contains a proxy configuration item. this configuration item is automatically converted to an Ext. data. proxy. ajax class instance. This instance contains the url parameters we have defined. this is equivalent to the following code:

new Ext.data.proxy.Ajax({    url: 'users.json',    model: 'User',    reader: 'json'});


There are two additional parameters-model and reader. when these parameters are used to create a proxy instance through Store, the default-Store has defined the Model, and the default Reader of Proxy is JsonReader.

Finally, we call store. load (), trigger the AjaxProxy action, send a request to the configured url (in this example, 'users. json '). because we are executing data reading, we will send a GET request. (for the definition of request methods, see actionMethods-by default, all read requests (read) are GET, while all write requests (create, update, destroy) are POST)

Configuration item

actionMethods: {    create : 'POST',    read   : 'GET',    update : 'POST',    destroy: 'POST'}

Restrictions

AjaxProxy cannot get data across domains. For example, if your program address is http://domainA.com, then you cannot get data from the http://domainB.com. This is because browsers have a built-in security mechanism to block AJAX cross-domain requests.

If you want to retrieve data from other domain names and you cannot set up a Proxy from the server (some programs running on your own server to forward requests to the http://domainB.com, but the client seems the data is still from http://domainA.com), you can use Ext. data. proxy. jsonP proxy and JSON-P technology so that as long as the server on the http://domainB.com supports JSON-P response, you can solve your cross-origin request problems. for more information, see Introduction to JsonPProxy.

Configure Reader and Writer

AjaxProxy can be configured with any type of Reader to interpret the server response. if you do not explicitly specify a Reader, JsonReader is used by default. you can use a simple property object to configure Reader. The proxy will automatically convert it to an instance of the Reader class:

Var proxy = new Ext. data. proxy. ajax ({model: 'user', reader: {type: 'xml', root: 'users'}); proxy. getReader (); // returns an XmlReader instance.

Generate Url

AjaxProxy automatically adds the sorting, filtering, paging, and grouping parameters to the generated url. You can use the following attributes to configure these parameters:

  • PageParam-controls how to send pages to the server (also see startParam and limitParam)
  • SortParam-controls how to send sorting information to the server
  • GroupParam-controls how to send group information to the server
  • FilterParam-controls how to send filter information to the server

Each request object sent by AjaxProxy is described by an Operation object. To illustrate how we generate a custom url, let's take a look at the Operation below:

var operation = new Ext.data.Operation({    action: 'read',    page  : 2});

Then we use this Operation to publish the request by calling read:

var proxy = new Ext.data.proxy.Ajax({    url: '/users'});proxy.read(operation); //GET /users?page=2

The Proxy class only needs to copy the page value in Operation. We can also customize how to send page data to the server:

Var proxy = new Ext. data. proxy. ajax ({url: '/users', pageParam: 'pagenumber', // default page}); proxy. read (operation); // GET/users? PageNumber = 2

Another solution is to configure Operation to send the start and limit parameters instead of page:

var operation = new Ext.data.Operation({    action: 'read',    start : 50,    limit : 25});var proxy = new Ext.data.proxy.Ajax({    url: '/users'});proxy.read(operation); //GET /users?start=50&limit;=25
Similarly, we can customize startParam limitParam.

Var proxy = new Ext. data. proxy. ajax ({url: '/users', startParam: 'startindex', // default start limitParam: 'pagesize' // default limit}); proxy. read (operation); // GET/users? StartIndex = 50 & pageSize; = 25
AjaxProxy will also send sorting and filtering information to the server. Let's see how to use Operation to indicate:

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'        })    ]});
When a Store containing sorters and filters parameters is used to load data, the above objects are generated internally. by default, AjaxProxy converts sorters and filters in JSON format to obtain the following results (note that the url will be encrypted before it is sent, so that it is easy to read and use unencrypted strings ):

var proxy = new Ext.data.proxy.Ajax({    url: '/users'});proxy.read(operation); //GET /users?sort=[{"property":"name","direction":"ASC"},{"property":"age","direction":"DESC"}]&filter;=[{"property":"eyeColor","value":"brown"}]
We can also customize these parameters. assume that the format of the sorting information read by our server is "sortBy = name # ASC, age # DESC ". we can configure AjaxProxy like this to provide this format:

Var proxy = new Ext. data. proxy. ajax ({url: '/users', sortParam: 'sortby', filterParam: 'filterby ', // our custom transcoding Method for sorting information-convert sorters to "name # ASC, age # DESC" encodeSorters: function (sorters) {var length = sorters. length, sortStrs = [], sorter, I; for (I = 0; I <length; I ++) {sorter = sorters [I]; sortStrs [I] = sorter. property + '#' + sorter. direction} return sortStrs. join (",") ;}}); proxy. read (operation) ; // GET/users? SortBy = name # ASC, age # DESC & filterBy; = [{"property": "eyeColor", "value": "brown"}]
We can also customize the encodeFilters method to transcode the filters information.


Ext. data. proxy. JsonP

The JsonP proxy is used when you want to load data from a domain name other than your own Application Server (cross-origin call ). for example, if your application runs on a http://domainA.com, you cannot load data from the http://domainB.com through Ajax, because the browser does not allow cross-origin ajax requests.

With the JsonP proxy, we can get rid of this restriction. Every time an AJAX request is made, the JsonP proxy injects<script>Tag. For example, if we want to load data from the http://domainB.com/users url, then a script tag is injected as follows:

<script src="http://domainB.com/users?callback=someCallback"></script>
After we inject the above tag, the browser will send a request to this url. through the callback in the url, we notify the domainB server: When the result is returned, please call this callback function and pass in the returned data. the call is successful as long as the server forms the response result in the following format:

Ext. regModel ("User", {fields: [{name: 'name', type: 'string'}], proxy: {type: 'jsonp ', // proxy url for cross-origin Interaction: 'http: // www.uspcat.com/extjs/person.php'}); var person = Ext. modelManager. getModel ('user'); person. load (1, {scope: this, success: function (model) {alert (model. get ('name '));}});



Ext. data. proxy. LocalStorage

LocalStorageProxy uses the latest HTML5 local database API to save Model data on the local client. the HTML5 local database is a key-Value Pair storage (for example, complex objects such as JSON cannot be stored). Therefore, LocalStorageProxy automatically serializes and deserializes data when saving and reading data.

The local database is very useful when saving user personal information, so you do not need to create a data structure on the server.

Ext.define('User', {    fields: ['id', 'name'],    extend: 'Ext.data.Model',    proxy: {        type: 'localstorage'    }});

Var store = new Ext. data. store ({model: 'user'}); store. add ({name: 'somnus'}); // Save the data store. sync (); // read data store. load (); store. each (function (record) {console.info (record. get ('name '));});



Ext. data. proxy. Memory

Memory proxy. This proxy uses simple local variables to store/read data, so its content will be cleared each time the page is refreshed.

Generally, this proxy is not directly used, but is used as the auxiliary service object of Store and provides a reader object for it when loading data. for example, suppose we have a User Model and Store, and some internal data we want to load, but the data format is not very suitable: in this case, we can use a MemoryProxy with JsonReader to read the data for the Store:

// The model object Ext. define ('user', {extend: 'ext. data. model ', fields: [{name: 'id', type: 'int'}, {name: 'name', type: 'string'}, {name: 'phone', type: 'string', mapping: 'phonenumber'}]}); // The data field is not defined in the model. The-field 'phone' is called 'phonenumber' var data = {users: [{id: 1, name: 'ed Spencer ', phoneNumber: '000000'}, {id: 2, name: 'abe Elias ', phoneNumber: '000000'}]}; // note how we set the 'root' of reader to meet the preceding data structure. var store = Ext. create ('ext. data. store', {autoLoad: true, model: 'user', data: data, proxy: {type: 'memory ', reader: {type: 'json', root: 'users '}}});

Var memoryProxy = Ext. create ("Ext. data. proxy. memory ", {data: data, model: 'user'}) data. push ({name: 'sunday', age: 1}); memoryProxy. update (new Ext. data. operation ({action: 'update', data: data}), function (result) {}, this); memoryProxy. read (new Ext. data. operation (), function (result) {var datas = result. resultSet. records; Ext. each (datas, function (model) {console.info (model. get ('name') ;}); var totalRecords = result. resultSet. total; alert ('read memory data, record always: '+ totalRecords );});


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.