ExtJS之 Proxy数据代理

213 篇文章 0 订阅
192 篇文章 0 订阅
ExtJS之 Proxy数据代理

代理种类截图:image

ExtJS提供的数据代理主要分为两大类:

1.客户端代理 (Ext.data.proxy.Client)

2.服务器代理(Ext.data.proxy.Server)

这两个类 都继承自 Ext.data.proxy.Proxy ,

客户端代理主要包括:Memory   WebStorage   SessionStorage   LocalStorage

服务器端代理包括:  Ajax   Rest  JsonP

Ext.data.proxy.Memory

//this is the model we will be using in the store     
          Ext.define('User', {      
              extend: 'Ext.data.Model',      
              fields: [      
      { name: 'id', type: 'int' },      
      { name: 'name', type: 'string' },      
      { name: 'phone', type: 'string', mapping: 'phoneNumber' }      
  ]      
          });

          //this data does not line up to our model fields - the phone field is called phoneNumber     
          var datas = {      
              users: [      
      {      
          id: 1,      
          name: 'Ed Spencer',      
          phoneNumber: '555 1234'      
      },      
      {      
          id: 2,      
          name: 'Abe Elias',      
          phoneNumber: '666 1234'      
      }      
  ]      
          };


          //创建memory代理      
          var memProxy = new Ext.data.proxy.Memory({

              model: 'User',     
              reader: { root: 'users' },      
              data: datas

          });     
          //读取数据      
          memProxy.read(new Ext.data.Operation(), function (result) {

              var total = result.resultSet.total;     
              alert("数据总条数为:" + total);

          })     

DOM Storage 分为两类, sessionStorage 和 localStorage

sessionStorage: 用于存储与 当前浏览器窗口关联的数据.窗口关闭后,sessionStorage中数据将无法使用

localStorage:      用于长期存储数据.窗口关闭,数据仍然可以访问, 所有浏览器窗口可以共享 数据.

下面看看一个 localStorage的例子

效果:image

Ext.define('Search', {     
                fields: ['id', 'query'],      
                extend: 'Ext.data.Model',      
                proxy: {      
                    type: 'localstorage',      
                    id: 'twitter-Searches'      
                }      
            });

            var store = new Ext.data.Store({     
                model: "Search"      
            });

            //添加数据     
            store.add({ query: 'Sencha Touch' });      
            store.add({ query: 'Ext JS' });      
            //保存数据      
            store.sync();

            //读取数据     
            store.load();

            var msg = [];     
            store.each(function (data) {      
                msg.push(data.get('id') + '-' + data.get('query'));

            })     
            alert(msg.join('\n'));

当 关闭浏览器,从今浏览此页面后,效果图:image

说明,localstorage 是长期存储数据的,即使关闭浏览器,数据仍然存在.

下面还要说明一点:LocalStorage代理如果没有指定id,则会使用 store的id,如果两个都没指点,那么就会抛出异常

Ext.data.proxy.SessionStorage

效果:image

Ext.define('Search', {     
               fields: ['id', 'query'],      
               extend: 'Ext.data.Model',      
               proxy: {      
                   type: 'sessionstorage',      
                   id: 'twitter-Searches'      
               }      
           });

           var store = new Ext.data.Store({     
               model: "Search"      
           });

           //添加数据     
           store.add({ query: 'Sencha Touch' });      
           store.add({ query: 'Ext JS' });      
           //保存数据      
           store.sync();

           //读取数据     
           store.load();

           var msg = [];     
           store.each(function (data) {      
               msg.push(data.get('id') + '-' + data.get('query'));

           })     
           alert(msg.join('\n'));

当关闭浏览器,从新浏览此页面时:image.

里面的数据没有增加,验证了刚才的说法.     

服务器端代理

服务器端代理会访问远程服务器资源,适合于长期保存重要的数据资料.

下面是 分页参数

image

//定义User模型

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

            //定义数据代理   
           var proxy = new Ext.data.proxy.Ajax({    
               model: 'User',    
               url: 'Handler.ashx',    
               reader: {    
                   type: 'json',   //jsonReader    
                   root: 'users'    
               }    
           });

           //创建请求参数对象

             var operation = new Ext.data.Operation({

               page: 2,   
               start: 10,    
               limit: 20,    
               action: 'read'   //请求动作

           });

           proxy.doRequest(operation, callback);  //发起请求   
           function callback(operation) { //请求的回调函数    
               //获取服务器返回的原始数据    
               var reText = operation.response.responseText;    
               //获取记录总数    
               var totalRecords = operation.resultSet.totalRecords;    
               //获取记录数组    
               var records = operation.resultSet.records;    
               alert(totalRecords);


           }    
服务器返回的数据:  {users:[{id:'" + id + "',name:'gao'}]} 

排序参数

参数信息:image

只需更改 上面程序的 operation配置即可

var operation = new Ext.data.Operation({

                sorters: [   
                new Ext.util.Sorter({    
                    property: 'id',    
                    direction: 'ASC'  //DESC    
                })    
                ],

                action: 'read'

            });

自定义排序参数:

image

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


           var proxy = new Ext.data.proxy.Ajax({    
               model: 'User',    
               url: 'Handler.ashx',    
               reader: {    
                   type: 'json',    
                   root: 'users'    
               },

               sortParam: 'sortParam',  //自定义排序参数名称

               encodeSorters: function (sorters) {//排序参数的数组,返回一个JSON-encodes的字符串

                   var length = sorters.length,   
                   sortArray = [],   //定义参数数组    
                   sorter, i;    
                   for (var i = 0; i < length; i++) {

                       sorter = sorters[i];   
                       sortArray[i] = sorter.property + '#' + sorter.direction;

                   }   
                   return sortArray.join(",");

               }   
           });

           var operation = new Ext.data.Operation({

               sorters: [   
               new Ext.util.Sorter({    
                   property: 'id',    
                   direction: 'ASC'  //DESC    
               }),    
               new Ext.util.Sorter({    
                   property: 'age',    
                   direction: 'DESC'    
               })

               ],

               action: 'read'

           });

           proxy.doRequest(operation, callback);   
           function callback(operation) {    
               //获取服务器返回的原始数据    
               var reText = operation.response.responseText;    
               //获取记录总数    
               var totalRecords = operation.resultSet.totalRecords;    
               //获取记录数组    
               var records = operation.resultSet.records;    
               alert(totalRecords);


           }    

过滤器参数

image

var operation = new Ext.data.Operation({

                filters: [   
              new Ext.util.Filter({

                  property: 'id',   
                  value: '2'    
              })    
              ]    
              ,

                action: 'read'

            });   

自定义过滤器参数 :

暂留

分组参数

image

var operation = new Ext.data.Operation({

                groupers: [

                    new Ext.util.Grouper({  
                   
                    property:'age',   
                    direction:'ASC'   
                    })   
               
                ]   
              ,

                action: 'read'

            });

Ext.data.proxy.Rest实例

image

Ext.regModel('User', {

               fields: ['id', 'name', 'age'],    
               proxy: {

                   type: 'rest',  //使用Ext.data.proxy.Rest代理    
                   url: 'Handler.ashx'     
               }

           });

           var u1 = Ext.ModelManager.create({ name: 'gao', age: 12 }, 'User');    
           u1.save();  //因为没有id所以调用 create方法

           var u2 = Ext.ModelManager.create({ id: 10, name: 'gao2', age: 12 }, 'User');    
           u2.save();   //因为有id,所以 执行update     
           var u3 = Ext.ModelManager.getModel('User');     
           u3.load(100); //调用read方法 ,读取id等于300的数据     
           var u4 = Ext.ModelManager.create({ id: 300, name: 'gao4', age: 11 }, 'User');     
           u4.destroy();  //

Ext.data.proxy.JsonP

暂留

Reader数据读取器

数据读取器的作用就是 将 数据代理 读取到的  原始数据 按照不同的规则进行解析,将解析后的数据

保存到Model模型对象 中,.

extJS主要数据解析器为:

1.Json数据读取器

2.XML数据读取器

3.数组数据读取器

Json读取器:

image

var userdata = {

                "total": 2000,    
                "users": [     
                            {     
                                "id": 22,     
                                "name": "gao",     
                                "orders": [     
                                                {     
                                                    "id": 30,     
                                                    "total": 100     
                                                },     
                                                 {     
                                                     "id": 320,     
                                                     "total": 1002     
                                                 }     
                                           ]

                            }    
                        ]


            }     
            //定义用户模型     
            Ext.regModel('User', {

                fields: ['id', 'name'],    
                hasMany: 'Order'

            });    
            //定义订单模型     
            Ext.regModel("Order", {

                fields: ["id", "total"],    
                belongTo: 'User'  //定义 order和user之间的多对一关系     
            })

            //创建 memory代理    
            var meoProxy = new Ext.data.proxy.Memory({

                model: 'User',    
                reader: {

                    type: 'json',    
                    root: 'users'     
                },     
                data: userdata

            })

            //读取数据    
            meoProxy.read(new Ext.data.Operation(), callBack);     
            function callBack(res) {     
                //获取总数据数     
                var count = res.resultSet.total;     
                //获取第一个用户信息     
                var user = res.resultSet.records[0];     
                //获取该用户的第一个账单信息     
                var order = user.orders().getAt(1);     
                alert("总数据数:" + count + '\n姓名:' + user.get('name') + '\n账单金额:' + order.get('total'));

            }

读取复杂的json数据:

image

代码:

var userdata = {


                "users": [     
                            {     
                                "id": 22,     
                                "name": "gao",     
                                "info": { "id": 22, "name": "gaoyu" }

                            }    
                        ]


            }     
            //定义用户模型     
            Ext.regModel('User', {

                fields: ['id', 'name']

            });

            //创建 memory代理    
            var meoProxy = new Ext.data.proxy.Memory({

                model: 'User',    
                reader: {

                    type: 'json',    
                    root: 'users',     
                    record: 'info'      //定位有效数据的位置     
                },     
                data: userdata

            })

            //读取数据    
            meoProxy.read(new Ext.data.Operation(), callBack);     
            function callBack(res) {     
                //获取第一个用户信息     
                var dd = res.resultSet.records[0];     
                alert('姓名:' + dd.get('name'));

            }

数组读取器

image


//定义用户模型     
Ext.regModel('User', {

    fields: ['id', 'name'],    
    proxy: //定义代理     
    {     
        type: 'ajax',     
        url: 'Handler.ashx',     
        reader: {     
            type: 'array'   //读取器类型为 数组     
        }     
    }

});    
var user = Ext.ModelManager.getModel('User');     
//通过代理读取数据     
user.load(1, {

    success: function (res) {

        alert(res.get('id'));    
    }     
})

服务器返回数据:  [[1,\'nill\']]

Writer数据写入器

主要用于将 数据代理 提交到服务端 的数据进行编码,.

主要写入器,有  JSON写入器和XML写入器

Json写入器使用:

image

//定义用户模型    
        Ext.regModel('User', {

            fields: ['id', 'name'],    
            proxy: //定义代理     
            {     
            type: 'ajax',     
            url: 'Handler.ashx',     
            writer: {     
                type: 'json'   //写入为json格式     
            }     
        }

    });    
    var user = Ext.ModelMgr.create({ id: 12, name: 'gao' }, 'User');     
    user.save({     
        success: function () { alert('save succeed!') },     
        failure: function () { alert('save failed!') }

    })

XML写入器

image

//定义用户模型    
           Ext.regModel('User', {

               fields: ['id', 'name'],    
               proxy: //定义代理     
               {     
               type: 'ajax',     
               url: 'Handler.ashx',     
               writer: {     
                   type: 'xml'   //写入为json格式     
               }     
           }

       });    
       var user = Ext.ModelMgr.create({ id: 12, name: 'gao' }, 'User');     
       user.save({     
           success: function () { alert('save succeed!') },     
           failure: function () { alert('save failed!') }

       })

遍历store

image

//定义用户模型    
          Ext.regModel('User', {

              fields: ['id', 'name'],    
              proxy: //定义代理     
              {     
              type: 'memory'


          }     
      })     
      var store = new Ext.data.Store({     
          autoLoad: true,     
          data: [{ id: 12, name: 'ss' }, { id: 11, name: 'zz'}],     
          model: 'User'


      })     
      //遍历store中元素     
      var msg = ['遍历:'];     
      store.each(function (res) {

          msg.push('id=' + res.get('id') + 'name=' + res.get('name'));    
      })     
      alert(msg.join('\n'));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值