Javascript - ExtJs - 数据

数据(ExtJs Data)

Ext.data命名空间

有关数据存储、读取的类都定义在Ext.data命名空间中。Ext的gridPanel、combobox的数据源都是来自Ext.data提供的类。该命名空间下的类支持数组、Json和xml数据。 

Ext.data.Connection

此类封装了Ajax,提供比传统Javascript异步传输数据更为简洁的方法,兼容了所有浏览器。它负责与服务端实现异步交互,并把从服务端的数据转交给Ext.data.Proxy进行处理。

配置.config  

url : String 
//请求的url。

extraParams : Object | String 
//请求传递的参数。如果配置在request方法中,此属性要改为params

method : 'GET' | 'POST' 
//请求的方式。

callback : function 
//请求完成后的回调函数,无论是成功还是失败,都会执行。

success : function(response) 
//请求成功时的回调函数。
//response:服务端的响应流(代表的就是服务端response对象),通过response.responseText获得服务端传输过来的Json数据

failure : function(response)
//请求失败时的回调函数
//response:服务端的响应流(代表的就是服务端response对象),通过response.responseText获得服务端传输过来的Json数据

scope : Object 
//回调函数的作用域。

form : Object | String 
//绑定的form表单。

isUpload : bool 
//是否执行文件上传。

headers : Object 
//请求的头部信息。

xmlData : Object 
//XML文档对象,可通过URL附加参数的方式发起请求。

JsonData : Json 
//Json对象,可通过URL附加参数的方式发起请求。

disableCaching : bool 
//是否禁用缓存,默认禁用。如果设为true则表示在发送GET方式的请求时, 为请求链接添加一个不重复的标识参数以禁用缓存。

timeout : delay 
//请求超时的微秒数,默认30秒。
View Code

方法.method 

request(config)
//发起请求并接收远程反馈,Ext.data.Connection的配置全部可写在request的配置中,区别在于extraParams要改为params。

abort([TransactionId])
    
//当同时有多个请求发生时,根据指定的事务id放弃其中的某一个请求。如果不指定事务id,则放弃最后一个请求。
//TransactionId: 事务ID

isLoading([TransactionId])
//根据事务id判断对应的请求是否完成。如果未指定事务id,就判断最后一个请求是否完成。
View Code

示例.example 

以下代码创建connection实例,并配置好它的各个参数,使用request向服务器发起请求并接收服务端的反馈。

Ext.onReady(function () {
    var conn = new Ext.data.Connection();
    conn.request({
        method: "Get",//请求方式
        timeout: 300,//请求超时时间
        autoAbort: false,//是否自动断开链接
        disableCaching: false,//是否禁用缓存
        defaultHeaders: { referer: "http://localhost:54480/" },  //请求的网址的头部
        url: "test", //asp.net mvc当前页面所属控制器下的Test方法,如果是其它控制器下的方法,需要填Controller/Action
        params: { //请求附带的参数
            name: 'sam'
        },
        success: function (response) {
            //将远程反馈的Json字符解析为Json对象
            var m = Ext.JSON.decode(response.responseText);
            Ext.Msg.alert("success",m.name);
        },
        failure: function () {
            Ext.Msg.alert("error", "http错误");
        }
    });
});

服务端

public string Test(string name)
{
    string s = $"{{name:'{name}'}}";
    return s;
}

Ext.data.Model

表示数据模型,可定义字段。此模型与数据库表相关联。如果你要建立自己的数据模型,就需要使你的类从Ext.data.Model派生。其new出的实例就是表的一条记录。你可以按需求设定Ext.data.Model的字段,不需要完全将数据库表的字段都定义在Model中,这要看你从数据库表中查询记录时所返回到客户端的记录中包含了哪些字段,没出现在Ext.data.Model字段中的数据,在客户端就不存在。另外,GridPanel的columns如果是设定为从Ext.data.Model中读取记录,那么即使Ext.data.Model定义了某个字段,但该字段并没出现在GridPanel的columns中,那么GrindPanel就不会显示它,但实际上它依然存在于内存中。最后 注意,Ext.data.Record是Ext.data.Model的一个属性。

创建数据模型 

//创建数据模型
Ext.define("employee", {
    extend: "Ext.data.Model",
    fields: [
        { name: "employeeName", type: "string", convert: function (value) { /*……convert是可选项,可对字段的值做出判断,可return一个新值*/ } },
        { name: "age", type: "int", convert: null },
        { name: "gender", type: "int" },
        { name: "IsMarried", type: "boolean", defaultValue: true, convert: null }, //defaultValue是可选项
        { name: "favit", type: "auto" } //auto类型表示数组,比如服务端返回的json数据的某个属性是一个数组
    ]
});

//如果Model的某个字段是一维数组,绑定数据的组件可以直接显示数组内容
//但如果是锯齿数组则需要渲染时指定读取数组的那一层
var column = [
    {
        text: "喜好",
        dataIndex: "favit",
        renderer: function () {
            return favit[1];
        }
    }
];

操作记录 

Ext.define("Employee", {
    extend: "Ext.data.Model",
    fields: [
        { name: "employeeID", type: "int" },
        { name: "employeeName", type: "string" }
    ]
});

var employee = new Employee({
    employeeID: 1,
    employeeName:"sam"
});

//获取记录
var name = employee.get("employeeName");
var name = employee.data["employeeName"];
var name = employee.data.employeeName;

//修改记录
employee.set("employeeName", "leo");
employee.data["employeeName"] = "leo";
employee.data.employeeName = "leo";

//Ext.data.Model不仅存储了字段的数据,同时还有很多额外的有关数据的信息
//使用get和set访问、修改记录就可以得到这些信息
//比如可以判断字段的值是否与之前不一致,
//不一致将被视为新值,修改值之前它会将旧值取出来存入modified属性中以便你有可能用得上
//而Ext.data.Model的data属性则只存储字段的数据,它不存储额外信息,
//所以推荐使用get和set访问器获取或修改字段。不过data属性自有它的优势,
//当你需要将记录拷贝一份时,data具备简洁的特性,这要比直接拷贝Ext.data.Model要节约资源得多

Model实例方法.method   

commit()
//提交数据,调用此方法后,会清空modified并将drity设为false。

reject()
//撤销修改,把修改后的数据还原为modified中存储的值,再清空modified并将drity设为false。

getChanges()
//获取修改的数据并包装成Json对象返回。
示例:
//处理表单
Ext.get("saveDataBtn").on("click", function () {
    //获取所有数据有被修改过的record
    var c = store.getModifiedRecords();
    var msg = "";
    c.forEach(function (record) {
        //被修改过的字段包装成Json返回
        //转化为Json字符
        var jsonStr=Ext.encode(record.getChanges());
        msg += "<br>" + jsonStr + "<br>";
    });
    Ext.Msg.alert(msg);
})

isModified()
//测试数据是否被修改。

copy()
//忽略drity,将记录拷贝一份,返回与store没有任何关系的Ext.data.Model副本。

save()
//使用代理发起REST请求。服务端会视为这是一个添加记录的请求。
示例:
//创建一条新记录
var stu2 = new Student({
    id:2,
    name: "korn"
});
stu2.save({
    //这有别于connection.request的success,以下参数中的record实际上=operation.responseText
    success: function (record, operation) {
        serverMsg = Ext.decode(operation.responseText).msg;
        Ext.Msg.alert(serverMsg);
    }
});

Model静态方法.staticMethod 

load(id,Json)
//id:远程请求时,从远程返回数据时,该数据被看做是本地数据模型的实例,你得配置该实例的id
Json:{ 
    scope: 作用域 , 
    failure: function(record, operation) ,    
    success: function(record, operation)                
}

destore()
//使用代理发起REST请求。服务端会视为这是一个删除记录的请求
//示例:
stu.destore({
    success: function (record, operation) {
        serverMsg = Ext.decode(operation.response.responseText);
        Ext.Msg.alert(serverMsg);
    }
});

save()
//使用代理发起REST请求。服务端会视为这是一个修改记录的请求

创建模型的代理

大部分情况你可能喜欢在Ext.data.Store中创建代理,但你可以在创建数据模型的同时直接为其创建一个代理。 

Ext.define('Student', {
    extend: 'Ext.data.Model',
    fields: [
        { name: 'ID', type: 'int' },
        { name: 'name', type: 'string' }
    ],
    proxy: {
        type: 'ajax',
        format: 'ashx',
        url: 'StudentHandler.ashx'
    }
});

 

Ext.data.Store

数据交互中介者,它负责对数据进行增、删、改、查 、排序、分组、分页。并将数据提供给gridPanel、treePanel和combobox等组件使用。可以将它视为本地数据库,把Ext.data.Model数组视为表。Ext.data.Store本身是一个空的数据容器,它有两个属性proxy(Ext.data.AjaxProxy)和reader(Ext.data.Reader)。proxy用于在本地或服务端获得数据,reader用于在proxy中读取转化数据为Ext.data.Model数组并存入store中(MixedCollection)。

加载本地数据

加载本地数据需要配置Ext.data.Store对象的两个属性:model和data,model(Ext.data.Model),data(Ext.data.Model数组)。每条记录(Ext.data.Model)都放在data数组里。

//加载本地数据到GridPanel中
Ext.define("Employee", {
    extend: "Ext.data.Model",
    fields: [
        { name: "employeeID", type: "int" },
        { name: "employeeName", type: "string" },
        { name: "employeeAge", type: "int" },
        { name: "employeeGender", type: "int", convert: function (val) { return val==1?"男":"女" } },
        { name: "IsMarried", type: "boolean", defaulValue: true, convert: function (val) { return val==false? "否":"是"}}
    ]
});

var sam = new Employee({
    employeeID: 1,
    employeeName: "sam",
    employeeAge: 32,
    employeeGender: 2,
    IsMarried:false
});

var leo = new Employee({
    employeeID: 2,
    employeeName: "leo",
    employeeAge: 42,
    employeeGender: 1,
    IsMarried: true
});

var dataArray = [sam, leo]; //Ext.data.Model数组

var datasource = Ext.create("Ext.data.Store", {
    data: dataArray, //数据在哪里
    model: "Employee" //集合是什么类型            
});

var grid =new Ext.grid.GridPanel({
    renderTo: "box",
    title: "员工信息表",
    width: 600,
    forceFit: true,
    store: datasource,
    columns: [
        { header: "编号", dataIndex: "employeeID" },
        { header: "姓名", dataIndex: "employeeName" },
        { header: "年龄", dataIndex: "employeeAge" },
        { header: "性别", dataIndex: "employeeGender" },
        { header: "婚否", dataIndex: "IsMarried" }
    ]
});

加载远程数据

加载远程数据需要配置Ext.data.Store对象的两个属性:model和proxy,proxy发起Ajax请求到远程取数据,将数据存入Store。

var store = new Ext.data.Store({
    model: "数据模型的名字",
    proxy: {
        type: 'ajax',
        url: 'xx.xml' | 'xx.ashx',
        reader: {
            type: 'xml' | 'json' | 'array'
        }
    }
});
using Newtonsoft.Json;

//服务端
namespace MyWeb.Controllers
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public int EmployeeAge { get; set; }
        public int EmployeeGender { get; set; }
        public bool IsMarried { get; set; }

    }
    public class DefaultController : Controller
    {
        public string Test(string name)
        {
            List<Employee> list = new List<Employee>
            {
                new Employee{ EmployeeID=1, EmployeeAge=32, EmployeeGender=2, EmployeeName="sam", IsMarried=false },
                new Employee{ EmployeeID=2, EmployeeAge=42, EmployeeGender=1, EmployeeName="leo", IsMarried=true }
            };
            return JsonConvert.SerializeObject(list);
        }
    }
}
//绑定远程数据
Ext.define("Employee", {
    extend: "Ext.data.Model",
    fields: [
        { name: "EmployeeID", type: "int" },
        { name: "EmployeeName", type: "string" },
        { name: "EmployeeAge", type: "int" },
        { name: "EmployeeGender", type: "int", convert: function (val) { return val == 1 ? "男" : "女" } },
        { name: "IsMarried", type: "boolean", defaulValue: true, convert: function (val) { return val==false? "否":"是"}}
    ]
});

var datasource = Ext.create("Ext.data.Store", {
    model: "Employee",
    autoLoad: true,
    proxy: {
        type: "ajax",
        url: "/default/test",
        reader: {
            type: "json"
        }
    }
});

var grid =new Ext.grid.GridPanel({
    renderTo: "box",
    title: "员工信息表",
    width: 600,
    forceFit: true,
    store: datasource,
    columns: [
        { header: "编号", dataIndex: "EmployeeID" },
        { header: "姓名", dataIndex: "EmployeeName" },
        { header: "年龄", dataIndex: "EmployeeAge" },
        { header: "性别", dataIndex: "EmployeeGender" },
        { header: "婚否", dataIndex: "IsMarried" }
    ]
});

配置.config   

autoLoad:bool | Json
//如果不喜欢在Store的外部使用load()方法加载数据,则可以使用此项,
//当autoLoad为true时会自动远程加载数据,否则不。
//autoLoad为Json时,需要在外部调用load方法,load方法自动将Json参数提交到服务端,
//如:autoLoad: { params: { getList: "true" } },注意,此配置项只会被外部的load方法发送一次,后续请求时,参数将变成null
//所以,如果有不止一次要向服务端发起请求且需要附带参数时,应将参数放置在proxy属性的extraParams中,因为假如有多次Ajax请求需要发起,比如绑定了服务端数据的下拉框在下拉时会自动发起新的Ajax请求,如果有提交到服务端的参数则应将参数配置在proxy中,如果类似这样的情况下把参数放在aotoLoad中,则只有首次加载时参数会成功提交,后续会变成null。将参数配置在proxy中就不会有这种情况发生。
//请求参数配置在proxy中的示例:
Ext.create("Ext.data.Store", {
    id: "GdStore",        
    model: "Gd",
    autoLoad:true,
    proxy: {
        type: "ajax",
        url: "GenderHandler.ashx",
        extraParams: { get: "true" } ,
        reader: {
            type: "json"           
        }
    }
});

storeId:string
//component应配置其Id以方便查找,而Store应配置storeId。获取Store应使用Ext.getStore(storeId)而非Ext.getCmp(componentId)

model : modelNameString
//指示数据模型

data : [ [] | { } ]
//指示本地的数据,如果是服务端的数据,改用proxy,数据可以是数组或Json

sorters : [ { property:"ID",direction:"DESC" | "ASC" },{ } ]
//指示排序,可指示多重排序

filters : [{ property : "ID" , value : /1/ },{}]
//指示过滤,经测试无效,原因不明,建议store加载完成后调用他的filter方法实现过滤

remoteSort : bool
//设为true会开启服务端排序,自动传递表示排序字段的参数sort和表示排序方式的参数dir到服务端。

proxy : { type: 'ajax', url: '服务端文件路径', reader : { type : 'json' | 'xml' | 'Array' , record : '表示一行记录的字段名' , root : 'xml中包含记录的根节点或json数据的根' } }
//配置代理获取远程数据,record 和 root 可选,只有在获取xml数据或有根的Json数据时会用到
//示例:
var store = new Ext.data.Store({
    model: "employee",
    proxy: {
        type: 'ajax',
        url: 'Data.xml',
        reader: {
            type: 'xml',
            record: 'employee',
            root: 'data'
        }
    }
});

方法.method.加载  

load(Json)
//加载远程数据,本地数据不需要load。在绑定数据的面板中如果更改了数据可再次调用此方法刷新数据
//Json配置如下:
//params : 传递到服务端的Json参数列表。如果是在load完成之后配置,则可以在外部使用等同的baseParams属设置load的参数。如:StoreComponent.baseParams.property=value。
//callback : fn(record,options,success,scope,add) 
//record:获得的记录
//options:参数列表
//success是否加载成功
//scope : 回调函数作用域
//add : bool 是否将新得到的数据添加到store记录集的末尾,如果不,则用新数据替换老数据。

reload()
//重新加载远程数据,如果params存在,则会自动应用上次load时的params。本地数据不需要reload。

loadData(data,IsAppend)
//data:可以被当成Ext.data.Model的实例数组或单个实例
//IsAppend:是否添加到store末尾
//动态加载新记录到store中,如果IsAppend为false,则新纪录会替换老记录。

方法.method.查找    

getAt ( RowIndex )
//搜索,根据索引行号获取记录对象,返回一个Ext.data.Model
//示例
var  datasource  =  Ext . create ( "Ext.data.Store" ,  {
     model :  "Employee" ,
     autoLoad :  true ,
     proxy :  {
         type :  "ajax" ,
         url :  "/default/test" ,
         reader :  {
             type :  "json"
         }
     },
     listeners :  {
         datachanged :  function  ( e ,  eOpts )  {
             var  model  =  e . getAt ( 0 ); 
             var  name  =  model . get ( "EmployeeName" );
             alert ( name );
         }
     }
});
 
getRange ( startRowIndex , endRowIndex )
//搜索,获取从startRowIndex到endRowIndex的记录,返回一个Ext.data.Model[ ]
 
getNewRecords ()
//获取新插入的记录,返回一个Ext.data.Model[ ]数组,没有记录返回false,插入数据可通过insert和add方法实现,前者可提供索引插入指定位置,后者在记录集末尾追加新记录
 
getModifiedRecords ()
//获取用户在编辑器上修改过数据的记录,返回一个Ext.data.Model[ ],存储有被修改过数据的记录。使用add或insert插入到store中的新数据会被视为脏数据一并返回
//示例:假如动态insert了一行,该行可能未输入数据,则提交修改时可以先做判断,删除空行再getModifiedRecords
var  store  =  Ext . getStore ( "TbRightStore" );
//获取脏数据前先删除未做改动的新行,因为新行会被getModifiedRecords当做脏数据返回
store . query ( "TbRightId" ,  0 ). each ( function  ( r )  {
     if  ( r . get ( "RightName" )  ==  "" )  {
         store . remove ( r );
     }
});
//获取被修改过的记录集
var  dirtyRows  =  store . getModifiedRecords ();            
  
getRemovedRecords ()
//获取被删除的记录,返回一个Ext.data.Model[ ]数组没有记录返回false
 
getCount ()
//获取总记录条数
 
getTotalCount ()
//如果无分页则与getCount()一样,否则,返回分页后的当前页的记录条数
 
indexOf ( record )
//查找并返回该记录的所在行索引如果存在过滤,被过滤的记录不会被发现
 
sum ( PropertyName , startIndex , endIndex )
//计算某列的从startIndex到endIndex列的数据的总和,如果没有后两个参数则计算该列数据全部的总和
 
find ( propertyName , RegExp , startRowIndex , anyMach , IsCase )
//搜索,根据参数进行特殊搜索find会自动遍历所有记录,找到符合规则的记录会立即返回行号,否则返回-1.
//property:要搜索的字段名
//RegExp:正则式或字符
//startRowIndex:起始行索引号,可选
//anyMach:是否不从头开始搜索,默认false,可选
//IsCase:是否区分大小写,可选
 
findBy ( fn , scope , startRowIndex )
//fn需要你设定搜索条件,函数必须返回true or falsefindBy会自动遍历所有记录,测试每一条记录是否符合fn设定的搜索规则,如果符合马上返回行号,否则继续遍历直到结束,没有符合则返回-1
//fn:自定义的搜索函数,接收表示记录的record参数和表示记录id的id参数
//scope:fn执行的作用域(即this 引用)默认是当前的store,可选
//startRowIndex:搜索的起始行索引号,可选
//fn:自动迭代函数,参数如下:
//record:当前迭代的记录
//index:行号
//示例:
var  index  =  datasource . findBy ( function  ( record ,  id )  {
     return  record . get ( "employeeName" )  ==  "sam"  &&  record . get ( "age" )  ==  32 ;
});
 
query ( propertyName , RegExp , anyMatch,IsCase )
//与find逻辑相同,但无startRowIndexfind返回数字,query返回Ext.util.MixedCollection对象包含了搜索到的记录
//示例:
var  MixedCollections =. each ( function ( record , index , count )
     record . get ( propertyName );    
});
//或:
if ( MixedCollections . getCount ()!= 0 )  {
     rec  =  MixedCollections . getRange ()[ 0 ]; //获取第一条记录
     val = rec . get ( "fieldName" )
}
 
queryBy ( fn , scope , startRowIndex )
//与findBy逻辑相同,findBy返回数字,queryBy返回Ext.util.MixedCollection对象包含了搜索到的记录

方法.method.添加 

/*-----以下的添加操作只是在view上立即显示新添加的数据,并不实际保存到Store,除非显示调用了commitChanges方法*/
add()
//在store末尾添加新的记录。
//示例:
datasource.add([[3, "leo", 52, 0, true]]);
//或
datasource.add([
    [3, "leo", 52, 0, true],
    [4, "lych", 25, 1, false]
]);
//或
datasource.add([
    { ID: 5, employeeName: "travis", age: 36, gender: 1, IsMarried: true },
    { ID: 6, employeeName: "livisis", age: 18, gender: 1, IsMarried: false }
]);

addSorted()
//与add逻辑类似,在store末尾添加新的记录。但如果store有排序,则新纪录也自动适应排序规则。推荐使用addSorted。

insert(index, dataModel)
//在索引处插入记录
//示例:如果gird绑定了这个存储器,使用inset插入记录后,grid会立即显示。通过getNewRecords()可获取新插入的行数据,该方法返回一个Ext.data.Model[]数组。
Ext.getStore("TbRightStore").insert(0, { TbRightId: 0, RightName: "此处输入权限名", Remark: "此处输入备注" });

方法.method.删除

remove(record)
record:Ext.data.Model实例或Ext.data.Model数组
//删除记录

removeAll()
//删除所有记录

方法.method.更新 

rejectChanges()
//撤销所有修改

commitChanges
//保存所有修改,保存修改后,被污染的数据所在的列显示的红色标识会自动消失

方法.method.排序 

sort("propertyName","ASC"|"DESC")
//对记录进行排序,如果只有参数1,则自动ASC排序,写两次则降序。
//示例:
sort("ID")//升序
sort("ID")//降序
store.insert(0, { TbRightId: 0, RightName: "此处输入权限名", Remark: "此处输入备注" }); //插入新数据
store.sort("index","ASC"); //根据索引排序,在grid中就是根据行号排序,会为新数据动态生成新的行号

sort( [ { property:"xxx" , direction : "ASC"|"DESC" }.{ property:"yyy" , direction : "ASC"|"DESC" } ] )
//对记录进行多重排序,xxx升序,在此基础之上yyy降序。

方法.method.过滤

filter ( propertyName , RegExp )
//propertyName:字段名称
//RegExp:正则式或字符
//条件过滤,无返回值
//示例:
datasource.filter("employeeName","s");//过滤该列中首字母是s的记录

filter( [ { property : "xxx" , value : "xxx" } , { filterFn : function(record) } ] )
//遍历所有记录并使用多个条件过滤筛选出满足条件的记录,无返回值。filterFn的record参数表示当前遍历中的记录对象。
//示例:
//过滤出employeeName列首字母是s且age大于30的记录
datasource.filter([
    { property: "employeeName", value: "s" },
    {
        filterFn: function (record) {
            var Is = record.get("age") > 30;
            return Is
        }
    }
]);

filterBy(fn,scope)
//遍历所有记录并使用回调函数设定过滤规则,每遍历一条记录都会回调fn,不返回值而是直接影响绑定了store的组件所显示的数据。
//示例:
//过滤出employeeName列首字母是s且age大于30的记录
datasource.filterBy(function (record, id) {
    var IsName = record.get("employeeName").charAt(0) == "s";
    var IsAge = record.get("age") > 30;
    return IsName && IsAge;
});

事件.event 

load  :  fn  (  store ,  records ,  success  )
//load方法同时也是一个事件,在读取数据的过程中触发。另外,在load方法中也可以添加一个callback回调,表示数据读取完毕后触发。如:
//数据存储器load完毕后将回调,该函数处理IsPic的列,该列本身显示数字,要将其替换为汉字
store . load ({
     callback :  function  ()  {
         var  count  =  this . getCount ();
         for  ( var  i  =  0 ;  i  <  count ;  i ++)  {
             var  record  =  store . getAt ( i );                       
             var  v  =  record . get ( "IsPic" );
             if  ( v  ==  "0" )  {
                 record . set ( "IsPic" ,  "否" );
                 alert ( record . get ( "IsPic" ));
             }
             else  {
                 record . set ( "IsPic" ,  "是" )
             }
         }
         this . commitChanges ();
     }
});

beforeload :  fn ()
//在加载数据之前触发,通过此事件可以动态追加Store的参数
//示例:    
beforeload :  function  ()  {  
     //向proxy.extraParams追加参数
     Ext . apply (  this . proxy . extraParams ,  {  参数1 :  值1  ,  参数2  :  值2  }  );
}

datachanged:fn ( this  ,  eOpts )
//数据在加载完成后 | 更新后 | 删除后触发

 

Ext.data.Proxy

作为数据代理类向服务端或本地请求数据。其下有11个代理的派生类,首先派生出ServerProxy(远程数据代理)和ClientProxy(本地数据代理)。派生层次结构如下:

ServerProxy

1.AjaxProxy

1-1.RestProxy

2.ScriptTagProxy(JsonP)

3.DirectProxy

ClientProxy

1.MemoryProxy

2.WebStorageProxy

2-1.SessionStorageProxy

2-2.LocalStorageProxy

配置.config 

url  :  urlString
//请求的路径

timeout  :  number
//请求超时微秒数,默认30000微秒,即30秒。

pageParam  :  string
//分页时,向服务端发送的分页页码,即指示要取第几页的数据。

startParam  :  string
//分页时,向服务端发送的提取记录的起始索引。

limitParam  :  string
//分页时,向服务端发送的每页显示的记录条数。

groupParam  :  string
//分组时,向服务端发送的分组的信息。
//示例:
//提交到服务的格式
//以gender列进行分组并升序或降序排
[{  property  :  'gender'  ,  direction  :  'ASC'  |  'desc'  }]

sortParam  :  string
//排序时,向服务端发送的排序的信息。
//示例:
[{  property  :  'age'  ,  direction  :  'ASC'  |  'desc'  }  ,  …… ]

filterParam  :  string
//过滤时,向服务端发送的过滤的信息。
//示例:
//过滤出city列的值是重庆的记录
[{  property  :  'city'  ,  value :  '重庆'  }]

使用RestProxy

这个代理比较明确的告知服务端它所要求的是什么类型的操作,一共有四种操作:增、删、改、查。服务端(ASP.NET)通过request.method就可知道RestProxy所要求的是四个之中的哪一个操作。在.net中,这个操作比较麻烦不建议使用,除了以下代码,你还必须要重写Url,修改程序映射(为aspx、ashx添加PUT、DELETE谓词),否则不会有效果。总体来说直接使用POST完成增删改查完全没问题,服务端要判断是哪种类型的操作只需要在客户端添加发送数据的参数,比如为params设置一个标识。 通常不需要手动创建Proxy对象而是在配置Ext.data.Store或配置Ext.data.Model时使用。

//服务端
string  methodType  =  context . Request . HttpMethod ;
switch  ( methodType )
{
     case  "POST" :
         context . Response . Write ( "{msg:'已添加'}" );
         return ;
     case  "GET" :
         var  student  =  new  {  id  =  32 ,  name  =  "sam"  };
         string  msg  =  JsonConvert . SerializeObject ( student );
         context . Response . Write ( msg );
         return ;
     case  "PUT" :
         context . Response . Write ( "{msg:'已更新}" );
         return ;
     case  "DELETE" :
         context . Response . Write ( "{msg:'已删除}" );
         return ;
}
//客户端
var  msg  =  "" ;
Ext . onReady ( function  ()  {

     Ext . define ( 'Student' ,  {
         extend :  'Ext.data.Model' ,
         fields :  [
             {  name :  'ID' ,  type :  'int'  },
             {  name :  'name' ,  type :  'string'  }
         ],
         proxy :  {
             type :  'rest' ,
             format :  'ashx' ,
             url : 'StudentHandler.ashx'
         }
     });

     var  stu  =  null ;
     var  serverMsg  =  null ;
     var  panel  =  new  Ext . Panel ({
         renderTo : Ext . getBody (),
         title :  '测试' ,
         width : 300 ,
         height : 100 ,
         tbar :  [
             {
                 text :  '查询' ,  handler :  function  ()  {
                     //向服务端发起rest请求
                     Student . load ( 'student1' ,  {
                         success :  function  ( record ,  operation )  {
                             stu  =  record ; //将获取到的服务端返回的Student类型的实例存入变量
                             serverMsg = Ext . decode ( operation . response . responseText ). name ;
                             panel . update ( serverMsg );
                         }
                     })
                 }
             },
             {
                 text :  "添加" ,  handler :  function  ()  {
                     //创建一条新记录
                     var  stu2  =  new  Student ({
                         id : 2 ,
                         name :  "korn"
                     });
                     stu2 . save ({
                         success :  function  ( record ,  operation )  {
                             serverMsg  =  Ext . decode ( operation . response . responseText ). msg ;
                             panel . update ( serverMsg );
                         }
                     });
                 }
             },
             {
                 text :  "删除" ,  handler :  function  ()  {
                     stu . destore ({
                         success :  function  ( record ,  operation )  {
                             serverMsg  =  Ext . decode ( operation . response . responseText ). name ;
                             panel . update ( serverMsg );
                         }
                     });
                 }
             },
             {
                 text :  '更新' ,  handler :  function  ()  {
                     Student . save ({
                         success :  function  ( record ,  operation )  {
                             stu  =  record ;
                             serverMsg  =  Ext . decode ( operation . response . responseText ). name ;
                             panel . update ( serverMsg );
                         }
                     })
                 }
             }
         ]
     });

});

 

 

Javascript - 学习总目录 

转载于:https://www.cnblogs.com/myrocknroll/p/7124057.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值