ExtJs4 (9) reader and writer

Source: Internet
Author: User
Tags xml reader

ExtJs4 (9) reader and writer

Ext. data. reader. Json

JSON Reader uses a proxy to read the return value in JSON format returned by the server. It is generally used to load the result into a storage set. For example, we will create the following:

Ext.define('User', {    extend: 'Ext.data.Model',    fields: ['id', 'name', 'email']});var store = Ext.create('Ext.data.Store', {    model: 'User',    proxy: {        type: 'ajax',        url : 'users.json',        reader: {            type: 'json'        }    }});

The preceding example creates a "User" model.

We have created the simplest type of JSON Reader object as possible, and told the Store's Proxy that we need to return a JSON Reader. store will automatically Store the model configuration so that we can replace it in the following ways:

reader: {    type : 'json',    model: 'User'}

The reader attribute we set is ready to read data from the server-at the same time, it will accept the following response:

[    {        "id": 1,        "name": "Ed Spencer",        "email": "ed@sencha.com"    },    {        "id": 2,        "name": "Abe Elias",        "email": "abe@sencha.com"    }]

Read Other JSON formats

If you already have a definition in JSON format and it does not look very similar to the ones we provide above, you can still use JsonReader's husband and wife configuration options to parse your format. for example, we can use the root configuration to parse the returned data as follows:

{    "users": [       {           "id": 1,           "name": "Ed Spencer",           "email": "ed@sencha.com"       },       {           "id": 2,           "name": "Abe Elias",           "email": "abe@sencha.com"       }    ]}

To resolve this, we only need to pass a root configuration to match the above "users ":

reader: {    type: 'json',    root: 'users'}

Sometimes the JSON structure is very complex. document databases like CouchDB often provide metadata for each record in such a nested structure:

{    "total": 122,    "offset": 0,    "users": [        {            "id": "ed-spencer-1",            "value": 1,            "user": {                "id": 1,                "name": "Ed Spencer",                "email": "ed@sencha.com"            }        }    ]}

The record data in the preceding example is an additional level nested in the "users" array, each "user" project contains additional metadata (for example, 'id' and 'value' in this example '). to parse the data in each 'user' item in the preceding json data, you must specify the record configuration as follows:

reader: {    type  : 'json',    root  : 'users',    record: 'user'}

Response metadata

The server can return metadata in its response. In addition to record data, the attribute set of the description data of the data itself or the reader for reconfiguration. To obtain metaData in the response, you must add a 'metadata' attribute to the root of the response data. metadata attributes can contain anything, but if Reader exists, it also supports a specific setting attribute. :

  • Root: name of the root attribute corresponding to the node whose response contains the recorded data
  • IdProperty: attribute name of the primary key field in the data
  • TotalProperty: Number of all records in the Data property name
  • SuccessProperty: name of the success status attribute in the response
  • MessageProperty: the attribute name of an optional response.
  • Fields: configure the field set used to reconfigure the Model before converting the response data to records.

    The Initialization Configuration of a Reader contains the following attributes ("fields" is generally included in the Model definition, so it is not displayed here ):

    reader: {    type : 'json',    root : 'root',    idProperty     : 'id',    totalProperty  : 'total',    successProperty: 'success',    messageProperty: 'message'}

    To obtain a response object that contains a different attribute defined in the above initialization, you need to use the 'metadata' attribute to dynamically reconfigure Reader. For example:

    {    "count": 1,    "ok": true,    "msg": "Users found",    "users": [{        "userId": 123,        "name": "Ed Spencer",        "email": "ed@sencha.com"    }],    "metaData": {        "root": "users",        "idProperty": 'userId',        "totalProperty": 'count',        "successProperty": 'ok',        "messageProperty": 'msg'    }}

    You can place any data you need in the 'metadata' attribute, and Reader will ignore these attributes, however, you can use the metaData attribute of Reader (this attribute also listens to the Proxy 'smetachange event ). (Of course, it can also be replaced by store ). Then, the application code can process the obtained metadata in any way.

    A simple example of how to use these to customize a suitable field set for the Model is a table (grid. By passing the 'fields' attribute, Reader automatically updates the Model internally, but these changes are not automatically reflected in the grid, unless you have updated the column configuration items. you can manually execute these operations, or use the standard grid configuration object column as the 'metadata' attribute, and then you can directly manage the grid. there is a very simple example to illustrate how to implement this situation:

    // Response format :{... "metaData": {"fields": [{"name": "userId", "type": "int" },{ "name": "name ", "type": "string" },{ "name": "birthday", "type": "date", "dateFormat ": "Y-j-m"},], "columns": [{"text": "User ID", "dataIndex": "userId", "width ": 40 },{ "text": "User Name", "dataIndex": "name", "flex": 1 },{ "text": "Birthday ", "dataIndex": "birthday", "flex": 1, "format": 'Y-j-m', "xtype": "datecolumn"}]}

    Reader can automatically read the configuration of the meta field set and recreate the Model based on the new field set. However, to process the new column configuration, you must process the metadata in the application code. The metadata processing time can be easily passed through store or proxy, for example:

        var store = Ext.create('Ext.data.Store', {        ...        listeners: {            'metachange': function(store, meta) {                myGrid.reconfigure(store, meta.columns);            }        }    });
    Ext. data. reader. Xml

    XML Reader is used by the proxy to read responses in the XML format returned by the server. This usually happens in the result of loading the Store. For example, we create a similar:

    Ext.define('User', {    extend: 'Ext.data.Model',    fields: ['id', 'name', 'email']});var store = Ext.create('Ext.data.Store', {    model: 'User',    proxy: {        type: 'ajax',        url : 'users.xml',        reader: {            type: 'xml',            record: 'user',            root: 'users'        }    }});

    The above example creates a 'user' Model. If you are not familiar with the Model, refer to the Model documentation for detailed explanations.

    Notify Store's {@ linkExt. data. proxy. proxy} We need an XML Reader to create a very simple XML Reader. Store will automatically pass the model parameters to Store, so we can pass parameters in the following way instead:

    reader: {    type : 'xml',    model: 'User',    record: 'user',    root: 'users'}

    The reader we set above is ready to read data from the server-at this time, reader will receive the following response:

    
        
            
                 
          
           1
                  
          
           Ed Spencer
                  
          
           ed@sencha.com
              
             
                 
          
           2
                  
          
           Abe Elias
                  
          
           abe@sencha.com
              
         
        

    First, the root option is used to define the root node. (A complete XML document must have only one root ). XML Reader then uses the configuration item record to pull the data into each record-in this example, we set the record to 'user', so each of the above Will be converted into objects in the User model.

    Note: XmlReader does not care whether the root node root and record elements are nested in a larger structure, so the following response data can still work effectively:

    
        
            
                 
                      
                           
             
             
              1
              
             
              Ed Spencer
              
             
              ed@sencha.com
              
                            
             
             
              2
              
             
              Abe Elias
              
             
              abe@sencha.com
              
                        
                   
              
         
        
    Response metadata

    The server can return additional data in the response, such as the number of Record Sets and response success status. They are generally included in the XML response as follows:

    
        
            
         
          100
             
         
          true
             
                 
          
           1
                  
          
           Ed Spencer
                  
          
           ed@sencha.com
              
             
                 
          
           2
                  
          
           Abe Elias
                  
          
           abe@sencha.com
              
         
        

    If these attributes exist in the XML response, they can be parsed and loaded by XmlReader to the Store. We can set the names of these attributes by specifying the last pair of configuration items:

    reader: {    type: 'xml',    root: 'users',    totalProperty  : 'total',    successProperty: 'success'}

    These final configuration items are not required for Reader creation, but can also be useful. When the server needs to report an error or indicate that a large amount of data is available, only one subset is returned.

    Response format

    Note: In order for the browser to parse the returned XML document, the Content-Type header in the HTTP response must be set to "text/xml" or "application/xml ". This is very important-otherwise XmlReader will not work properly





Related Article

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.