本示例将使用第
2
章定义的
T_Categories
表,结合
DataWrite
和
RowEditor
直接在
Grid
中实现添加、修改和删除操作。
首先创建一个“
grid.html
”的页面文件,把需要的
Ext
文件包含在文件里,还需要包含
RowEditor
的样式文件和脚本文件。
接着在
onReady
中初始化
QuickTips
,代码如下所示。
Ext.QuickTips.init();
这是
RowEditor
显示错误信息用的,必须加上。
接着定义一个
HttpProxy
,代码如下所示。
var proxy = new Ext.data.HttpProxy({
api: {
read
: 'grid.ashx?act=list',
create : 'grid.ashx?act=create',
update: 'grid.ashx?act=update',
destroy: 'grid.ashx?act=del'
}
});
在
HttpProxy
的定义中,列表、增加、编辑和删除
的提交地址都是“
gird.ashx
”,通过
act
参数来区分这
4
个操作。
接着定义一个
JsonReader
,代码如下所示。
var reader = new Ext.data.JsonReader({
totalProperty: 'total',
successProperty: 'success',
idProperty:"id",
root:
'rows'
}, [
{name: 'id'},
{name:
'cid',allowBlank: false},
{name:
'title', allowBlank: false},
{name:
'desc'}
]);
在定义中,
id
字段与
cid
字段是一样的,之所以要分开定义是因为
T_Categories
表的
id
是手动输入的,不是自动产生的,而
Store
在增加记录提交数据时,如图
8-21
所示,
id
字段提交是
Store
自动生成的
id
,并不是用户输入的
id
,因而后台将无法处理这些数据。所以在这里使用了两个字段,不过,这又会产生另外一个问题,这在后面会谈到。如果
id
是自动生成的,可不用这样处理,直接一个
id
就行了。
接着定义一个
JsonWriter
,代码如下所示。
var writer = new Ext.data.JsonWriter({
encode:
true,
writeAllFields: true
});
在上面代码中,参数
encode
设置为
true
,则提交的数据是如图
8-21
所示的格式
,所有数据都编码成
JSON
格式,由
rows
参数提交到服务器。注意,“
rows
”参数是
JsonReader
定义中的参数
root
的定义值,譬如,在
JsonReader
的定义中,
root
的值为“
data
”,则图
8-21
中提交的数据是“
data {
…
}
”,而不是“
rows
{
…
}
”。
如果
encode
设置为
false
,则提交的数据形式如图
8-22
所示,这将没有提交参数名称,而其中的“
rows
”也是
JsonReader
定义中
root
的值。
参数
writeAllFields
的作用是,当提交时,如果设置为
true
,则提交所有字段,如果为
false
,则只提交修改过的字段。
接着定义一个
Store
,代码如下所示。
var store = new Ext.data.Store({
proxy: proxy,
reader: reader,
writer: writer,
autoSave: true,
autoLoad:true,
listeners: {
write : function(store, action, result,
res, rs) {
if(action==Ext.data.Api.actions.destroy){
Ext.Msg.alert("
信息
",res["msg"]);
}
},
exception : function(proxy, type, action,
options, res, arg) {
if (type === 'remote') {
Ext.Msg.show({
title: '
错误
',
msg: res.message,
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
}else{
if(action==Ext.data.Api.actions.create){
var
row = Ext.decode(options.params["rows"]);
if(row["id"]){
rec=store.getById(row["id"]);
if(rec)
store.remove(rec);
}
}
var
o= Ext.decode(res.responseText);
if(o["msg"]){
Ext.Msg.alert("
错误
",o["msg"]);
}
}
}
}
});
定义中,
proxy
、
reader
和
writer
都是之前定义好的。参数
autoSave
的作用是数据被改变时将自动提交数据,参数
autoLoad
表示自动加载数据,在其中还监听了
write
事件和
exception
事件。
write
事件将在数据提交成功后触发,而
exception
事件则在数据提交失败后触发。在
write
事件中,当删除数据成功时,会显示服务器端返回的提示信息。在
exception
事件中,如果服务器端文件运行存在错误,则提示错误信息。如果不是,则判断是否在创建新记录时发生错误,如果是,则在
Store
中删除新增加的记录,最后显示服务器端返回的错误信息。
接着定义
RowEditor
,代码如下:
var editor = new
Ext.ux.grid.RowEditor({
saveText: '
保存
',
cancelText:'
取消
',
listeners:{
beforeedit:function(rowedit,index){
//
如果是
update
状态不允许修改
id
var rec=store.getAt(index);
if(rec.data.cid){
ideditor.disable();
}else{
ideditor.enable();
}
}
}
});