Ext Js简单Grid创建使用及AJAX处理
在使用Ext Js对于Grid组件使用必不可少的,对于它的掌握也是需要的。简单贴一些代码,看看Grid的创建使用,就不细讲每一步了,代码注释还可以,不明白的可以在评论中写一下,或发邮件给我,一定帮助解答,欢迎交流。
1.简单Ext Js Grid的创建使用(创建Ext.grid.GridPanel需要store(proxy\reader)\colModel)
//创建GridPanel对象 function createGrid() { //创建表格的列信息 var cm1 = new Ext.grid.ColumnModel([ { header: '编号', dataIndex: 'id', width: 80, sortable: true }, //sortable:是否排序,width:重设列宽 {header: '名称', dataIndex: 'name', sortable: true }, { header: '描述', dataIndex: 'desn', id: 'desn' } //实现自动扩展列的效果,设置对应的列的id赋值,autoExpandColum ]); //添加数据信息 var data = [ ['1', 'name1', 'desn1'], ['2', 'name2', 'desn2'], ['3', 'name3', 'desn3'], ['4', 'name4', 'desn4'], ['5', 'name5', 'desn5'] ]; var dataObj = Ext.data.Record.create([//创建Record对象结构 {name: "id" }, { name: "name" }, { name: "desn" } ]); //创建数据存储对象 var ds = new Ext.data.Store({ proxy: new Ext.data.MemoryProxy(data), reader: new Ext.data.ArrayReader({}, [//此处的结构还可以使用上文对象,dataObj {name: 'id' }, { name: 'name' }, { name: 'desn' } ] ) }); ds.load(); //这个非常必要,load为自动传入数据;loadData手动传入数据 //表格列模型定义好了,原始数据和数据转换完成,再装配到一起,Grid就创建成功了 var grid = new Ext.grid.GridPanel({ renderTo: "divGrid", //rendTo属性指示将表格渲染到什么地方 width: 500, height: 500, store: ds, //数据 colModel: cm1, //列显示 stripeRows: true, //斑马线效果 loadMask: true, //读取数据遮罩和提示,Loading.... enableColumnMove: false, //取消列的拖放 enableColumnResize: true, //取消列的大小改变 viewConfig: { forceFit: true//自动填满Grid,填满父容器"grid"的大小, } }); }
2.简单封装一些Grid的创建,添加对于时间数据的显示控制
View Code
function testGrid() { var myColModel = new Ext.grid.ColumnModel([//列模式 new Ext.grid.RowNumberer(), //行号 {header: "ID", dataIndex: "id", sortable: true }, { header: "Name", dataIndex: "name", sortable: true }, { header: "Description", dataIndex: "desn", sortable: true }, { header: "DateTime", dataIndex: "lastDate", type: "date", renderer: Ext.util.Format.dateRenderer("Y年m月d日 H时m分s秒") }//添加一列日期,设置日期格式 ]); var data = [//数据 ["001", "张三", "学生", '2009-09-12T09:09:09'], ['002', '李四', '工作', '2009-09-20T09:09:09'], ['003', '王五', '教师', '2010-10-10T09:09:09'], ['004', '李白', '诗人', '2011-10-01T09:09:09'], ['005', 'QQ', '娱乐', '2012-09-09T09:09:09'] ]; var dataRecord = Ext.data.Record.create([//创建Record对象 {name: "id" }, { name: "name" }, { name: "desn" }, { name: "lastDate", type: "date", dateFormat: "Y-m-dTH:m:s"}//设定日期读取格式 ]); var myStore = new Ext.data.Store({//创建Store对象 proxy: new Ext.data.MemoryProxy(data), //创建指定代理 reader: new Ext.data.ArrayReader({}, dataRecord)//创建指定数组读取器 }); myStore.load(); //加载数据 var grid = new Ext.grid.GridPanel({ renderTo: Ext.getBody(), width: 400, height: 500, style: "margin-left: 100px; margin-top: 100px", store: myStore, colModel: myColModel, loadMask: true, stripeRows: true, enableColumnMove: true, enableColumnResize: true, viewConfig: { forceFit: false//如果强制填充,将不会有滚动条显示 } }); //行和列自动根据Grid的大小和数据的显示滚动条 grid.setAutoScroll(true); }
View Code
//本地数据创建GridPanel function createGridPanel() { var grid = new Ext.grid.GridPanel({ width: 600, height: 300, frame: true, iconCls: "icon-grid", title: "GridTest", stripRow: true, loadMask: true, enableColumnMove: true, enableColumnResize: true, sm: createSelModel(), store: createStore(), colModel: createColumns(), renderTo: Ext.getBody(), viewConfig: { forceFit: true}//自动填充 }); } //创建GridColumns function createColumns() { var cols = new Ext.grid.ColumnModel({ defaults: { width: 100, sortable: true }, columns: [ { id: "company", header: "Company", dataIndex: "company", width: 120, sortable: true }, { header: "Price", dataIndex: "price", renderer: Ext.util.Format.usMoney }, { header: "Change", dataIndex: "change" }, { header: "LastUpdate", dataIndex: "lastDate", type: "date", renderer: Ext.util.Format.dateRenderer("Y年m月d日") } ] }); return cols; } //创建数据存储Store function createStore() { //符合格式的数据 var myData = [ ["company1", 1, "change1", "2009-09-17"], ["company2", 2, "change2", "2012-10-10"], ["company3", 3, "change3", "2010-06-10"], ["company4", 4, "change4", "2012-07-10"], ["company5", 5, "change5", "2010-05-10"], ["company6", 6, "change6", "2012-11-10"] ]; //创建Reader,按指定格式读取 var myReader = Ext.data.Record.create([ { name: "company" }, { name: "price" }, { name: "change" }, { name: "lastDate", type: "date", dateFormat: "Y-m-d"}//注意时间转换 ]); //创建数据集对象Store var store = new Ext.data.Store({ proxy: new Ext.data.MemoryProxy(myData), reader: new Ext.data.ArrayReader({}, myReader) }); store.load(); //load为自动传入数据;loadData手动传入数据 return store; } //创建选中模式 function createSelModel() { var selModel = new Ext.grid.RowSelectionModel({ singleSelect: true }); return selModel; }
3.简单可编辑Grid的AJAX操作:加载、添加、修改、删除数据
前台ExtJs的创建EditorGridPanel,以及加载、添加、修改、删除操作:
Ext.onReady(function () { gridAjaxTest(); }); function gridAjaxTest() { var checkSelModel = new Ext.grid.CheckboxSelectionModel({ checkOnly: true }); //单行选中{ singleSelect: true },checkBox显示 var cm = new Ext.grid.ColumnModel([//设置列的结构 checkSelModel, { header: '学生ID', dataIndex: 'StuID', width: 80 }, { header: '学生姓名', dataIndex: 'StuName', editor: new Ext.grid.GridEditor(new Ext.form.TextField({})) }, { header: '学生年龄', dataIndex: 'StuAge', editor: new Ext.grid.GridEditor(new Ext.form.TextField({ allowBlank: false })) }, { header: '学生性别', dataIndex: 'StuSex', editor: new Ext.grid.GridEditor(new Ext.form.ComboBox({ store: ['男', '女'], triggerAction: 'all', editable: false, autoSelect: true })) }, { header: '学生描述', dataIndex: 'StuDesp', id: 'StuDesp', editor: new Ext.grid.GridEditor(new Ext.form.TextArea({ allowBlank: false })) }, { header: '入学日期', dataIndex: 'StuDate', width: 150, editor: new Ext.grid.GridEditor(new Ext.form.DateField({ editable: false, format: 'Y-m-d', value: new Date().format('Y-m-d') })) } ]); var ds = new Ext.data.JsonStore({//设置数据绑定 url: 'TestGridAjax.ashx', //请求地址 baseParams: { Option: 'GetData' }, fields: ['StuID', 'StuName', 'StuAge', 'StuSex', 'StuDesp', 'StuDate']//绑定字段 }); ds.load(); var gridAjax = new Ext.grid.EditorGridPanel({//可编辑GridPanel width: 800, height: 500, renderTo: Ext.getBody(), style: { marginLeft: 100, marginTop: 100 }, store: ds, //数据 colModel: cm, //列显示结构 //sm:checkSelModel,//checkBox显示选中 sm: new Ext.grid.RowSelectionModel(), //单行选中{ singleSelect: true },不设为多行选中 loadMask: true, stripeRows: true, autoExpandColumn: 'StuDesp', //设置一列自动填充剩余部分 clicksToEdit: 2, //双击触发修改 tbar: new Ext.Toolbar([ { text: '添加', handler: function () { addData(gridAjax); } }, '-', //添加操作 {text: '删除', id: 'btnDelete', handler: function () {//删除操作 Ext.MessageBox.confirm('信息提示', '你确定要删除吗?', function (btn) { if (btn == 'yes') { delData(gridAjax); } }); } }, '-', { text: '保存', id: 'tbnSave', handler: function () { saveData(gridAjax); } }//保存操作 ]) }); } function addData(gridAjax) {//添加操作,传入GridPanel对象 var stu = new Ext.data.Record({ StuID: 0, StuName: '学生名', StuAge: 20, StuSex: '', StuDesp: '', StuDate: '' }); //添加默认数据 gridAjax.stopEditing(); gridAjax.store.insert(0, stu); //在第0行插入该记录 gridAjax.startEditing(0, 1); } function delData(gridAjax) {//删除数据(实现单行\多行记录删除) if (gridAjax.selModel.getCount() > 0) {//获取选中的行总数 //var record = gridAjax.selModel.getSelected(); //获取选中的单条记录 var records = gridAjax.selModel.getSelections(); //获取选中的所有记录 var stuIDS = ""; //要删除学生ID集合 for (var i = 0; i < records.length; i++) { stuIDS += records[i].data.StuID + ","; } if (stuIDS.indexOf(',')) { stuIDS = stuIDS.substring(0, stuIDS.lastIndexOf(',')); } //去掉最后一个"," Ext.Ajax.request({ method: 'POST', //请求方式大小写敏感 url: 'TestGridAjax.ashx', params: { Option: 'DeleteData', JsonData: stuIDS }, success: function (response, options) {//执行成功 gridAjax.store.remove(records); //数据库删除成功,前台删除选中的所有记录 gridAjax.reconfigure(gridAjax.store, gridAjax.colModel); //绑定对象并刷新 Ext.MessageBox.alert('信息提示', Ext.util.JSON.decode(response.responseText).Msg); //获取后台返回的Json数据Msg键的值 }, failure: function (response, options) { Ext.MessageBox.alert('信息提示', Ext.util.JSON.decode(response.responseText).Msg); } }); } else { Ext.MessageBox.alert('信息提示', '请选择你要删除的数据!'); } } function saveData(gridAjax) {//保存数据 var records = null; //清空数据组数据 var jsonData = ""; //清空Json格式数据 records = gridAjax.store.getModifiedRecords(); //获取所有修改的记录(添加\修改的记录) if (records.length <= 0) { return; } jsonData = '['; //Json数据 for (var i = 0; i < records.length; i++) {//遍历集合,将所有修改的拼接成Json数据 jsonData += String.format("{'StuID':{0},'StuName':'{1}','StuAge':{2},'StuSex':'{3}','StuDesp':'{4}','StuDate':'{5}'},", records[i].data.StuID, records[i].data.StuName, records[i].data.StuAge, records[i].data.StuSex, records[i].data.StuDesp, records[i].data.StuDate == '' ? new Date().format('Y-m-d') : records[i].data.StuDate.format('Y-m-d')); //如果为空转换为当前时间 } if (jsonData.indexOf(',')) { jsonData = jsonData.substr(0, jsonData.lastIndexOf(',')); } //去除最后一个"," jsonData += "]"; Ext.Ajax.request({ method: 'POST', //请求方式大小写敏感 url: 'TestGridAjax.ashx', params: { Option: 'SaveData', jsonData: jsonData }, success: function (response, opts) { var json = Ext.util.JSON.decode(response.responseText); Ext.MessageBox.alert('信息提示', json.Msg) }, //获取返回的Json数据 failure: function (response, opts) { Ext.MessageBox.alert('信息提示', Ext.util.JSON.decode(response.responseText)); } }); gridAjax.store.reload(); }
后台对于AJAX的响应操作创建一般处理程序.ashx文件,对于加载、增、删、改数据的响应,使用List集合模拟数据操作,对于List集合转化为Json和Json转化为List集合,即Json的序列化和反序列化操作:
(注意对于命名空间的引入以及JavaScriptSerializer和DataContractJsonSerializer两个序列化器的差异,可参见:小心DataContractJsonSerializer和JavaScriptSerializer的内部实现差异)
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Web; using System.Web.Script.Serialization; namespace WebExtJS.WebTest { /// <summary> /// TestGridAjax1 的摘要说明 /// </summary> public class TestGridAjax1 : IHttpHandler { private List<Student> listStus = null;//(或全局静态变量)学生数据集合 public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; listStus = GetDataSet();//初始化数据,假的模拟数据 string strOption = context.Request["Option"] != null ? context.Request["Option"].Trim().ToString() : null; string jsonData = context.Request["JsonData"] != null ? context.Request["JsonData"].Trim().ToString() : string.Empty; string outPutMsg = string.Empty; switch (strOption) { case "GetData": outPutMsg = JavaScriptSerialize(listStus); break;//获取数据 case "SaveData": outPutMsg = SaveData(jsonData); break;//保存数据 case "DeleteData": outPutMsg = DeleteData(jsonData); break;//删除数据 case "SaveSingle": outPutMsg = SaveSingle(context.Request); break;//保存单条记录 case "GetPagingData": outPutMsg = GetPagingData(context.Request); break;//分页查询处理 default: break; } context.Response.Write(outPutMsg);//将处理后的Json数据传出 context.Response.End(); } /// <summary> /// JS序列化,将对象转换为Json数据 /// 注意:JS对于List对象的,处理需要对传出的Json数据,进行简单字符替换 /// </summary> /// <param name="listStus">List集合</param> /// <returns>序列化的数据</returns> private string JavaScriptSerialize(List<Student> listStus) { string json = string.Empty; if (listStus != null && listStus.Count > 0) { JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); json += jsSerializer.Serialize(listStus).Replace("\"", "'");//字符处理 } //json = json.Insert(0, "{'TotalCount':'" + listStus.Count + "',rows:");//这是数据保存统一的输出格式需要的 //json = json.Insert(json.Length, "}"); return json; } /// <summary> /// JS反序列化操作 /// 注意:根据前面设计的数据格式,可以直接反序列化 /// </summary> /// <param name="json">前台格式的数据</param> /// <returns>List集合</returns> private List<Student> JavaScriptDeserialize(string json) { List<Student> tempStus = new List<Student>(); if (!string.IsNullOrEmpty(json)) { JavaScriptSerializer jsDeserializer = new JavaScriptSerializer(); tempStus = jsDeserializer.Deserialize<List<Student>>(json); } return tempStus; } /// <summary> /// Json序列化,将对象转化为Json数据 /// 注意:对于C#处理的Json可以直接使用 /// </summary> /// <param name="listStus"></param> /// <returns></returns> private string JsonSerialize(List<Student> listStus) { string json = string.Empty; if (listStus != null && listStus.Count > 0) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(List<Student>)); MemoryStream ms = new MemoryStream(); jsonSerializer.WriteObject(ms, listStus); json += Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); } return json; } /// <summary> /// Json反序列化操作 /// 注意:根据前面提供的数据需要小小的字符串处理 /// </summary> /// <param name="json"></param> /// <returns></returns> private List<Student> JsonDeserialize(string json) { List<Student> tempStus = new List<Student>(); if (!string.IsNullOrEmpty(json)) { json = json.Replace("'", "\"");//字符串处理 DataContractJsonSerializer jsonDeserializer = new DataContractJsonSerializer(typeof(List<Student>)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); tempStus = (List<Student>)jsonDeserializer.ReadObject(ms); } return tempStus; } /// <summary> /// 根据前台传入的Json数据,保存数据 /// </summary> /// <param name="jsonData"></param> /// <returns>是否成功的Json数据</returns> private string SaveData(string jsonData) { string message = "{'Msg':'保存失败!'}"; List<Student> tempStudents = new List<Student>(); if (!string.IsNullOrEmpty(jsonData)) { //tempStudents = JavaScriptDeserialize(jsonData);//JS反序列化 tempStudents = JsonDeserialize(jsonData);//C#反序列化 int rows = AddAndUpdateStus(tempStudents);//添加修改操作 if (rows > 0) { message = "{'Msg':'传出Json数据,保存成功!'}";//向前台输出Json数据 } else { message = "{'Msg':'传出Json数据,保存失败!'}"; } } return message; } /// <summary> /// 单条数据的保存操作 /// </summary> /// <param name="request"></param> /// <returns></returns> private string SaveSingle(HttpRequest request) { string message = "{success:false,Msg:'保存失败!'}"; try {//表单提交,HttpRequest获取所有的对象 string stuID = request["StuID"].ToString() == "" ? "0" : request["StuID"].ToString(); string stuName = request["StuName"].ToString(); int stuAge = int.Parse(request["StuAge"].ToString()); string stuSex = request["StuSex"].ToString(); string stuDesp = request["StuDesp"].ToString(); string stuDate = request["StuDate"].ToString(); Student stu = new Student() { StuID = stuID, StuAge = stuAge, StuName = stuName, StuSex = stuSex, StuDesp = stuDesp, StuDate = stuDate }; AddAndUpdateStus(stu); message = "{success:true,Msg:'保存成功!'}"; } catch (Exception exp) { throw new Exception("异常信息"); } return message; } /// <summary> /// 根据传入的学生ID集合删除数据,可以单条\多条记录删除,这里执行数据库删除 /// </summary> /// <param name="jsonData"></param> /// <returns></returns> private string DeleteData(string jsonData) { string message = "{'Msg':'删除失败!'}"; if (!string.IsNullOrWhiteSpace(jsonData)) { List<Student> tempLambStus = listStus.FindAll(student => jsonData.Contains(student.StuID));//Lambda查询获取数据 List<Student> tempLinqStus = new List<Student>((from student in listStus where jsonData.Contains(student.StuID) select student).ToList());//Linq查询获取数据转化为List集合 listStus.RemoveAll(student => jsonData.Contains(student.StuID));//删除符合条件的记录 message = "{'Msg':'删除成功!'}"; } return message; } /// <summary> /// 添加\修改操作,这里执行数据库的增\改 /// </summary> /// <param name="stus"></param> /// <returns></returns> private int AddAndUpdateStus(List<Student> stus) { int rows = 0; if (stus.Count > 0) { try { foreach (Student stu in stus)//遍历所有集合 { AddAndUpdateStus(stu);//对于单条数据的处理 } rows = stus.Count;//返回影响行数 } catch (Exception exp) { rows = -1; } } return rows; } /// <summary> /// 对于单条记录的处理,这里执行单条记录的增\改 /// </summary> /// <param name="stu"></param> private void AddAndUpdateStus(Student stu) { if (stu.StuID == "0")//ID为0表示新加记录 { listStus.Add(stu); } else {//根据ID获取对象,修改数据 Student oldStu = listStus.Find(student => student.StuID == stu.StuID);//查找该对象是否存在 //var oldStudent = from student in listStus where student.StuID == stu.StuID select student;//获取符合ID的对象 //var stuIDS = from student in listStus where student.StuID == stu.StuID select student.StuID;//获取所有的ID集合 oldStu.StuAge = stu.StuAge; oldStu.StuDate = stu.StuDate; oldStu.StuDesp = stu.StuDesp; oldStu.StuName = stu.StuName; oldStu.StuSex = stu.StuSex; } } /// <summary> /// 对于数据的分页处理 /// </summary> /// <param name="request"></param> /// <returns></returns> private string GetPagingData(HttpRequest request)//这里执行数据库分页操作 { string json = string.Empty; int start = request["start"] != null ? int.Parse(request["start"]) : 0;//开始记录数 int limit = request["limit"] != null ? int.Parse(request["limit"]) : 2;//页大小 var stus = (from student in listStus orderby student.StuID select student).Skip(start).Take(limit);//Linq分页查询 List<Student> tempLinqStus = new List<Student>(stus.ToList());//转化为List集合 List<Student> tempLambStus = listStus.OrderBy(student => student.StuID).Skip(start).Take(limit).ToList();//Lambda分页查询 //字符拼接,指定总记录数(totalProperty)和显示数据的根(root) json = JavaScriptSerialize(tempLinqStus).Insert(0, "{'TotalCount':'" + listStus.Count + "',Datas:"); json = json.Insert(json.Length, "}"); //json = JsonSerialize(tempLinqStus).Insert(0, "{\"TotalCount\":\"" + listStus.Count + "\",Datas:"); //json = json.Insert(json.Length, "}"); return json; } /// <summary> /// 初始化数据,这里执行数据库查询初始化操作 /// </summary> /// <returns></returns> private List<Student> GetDataSet() { List<Student> listStus = new List<Student> { //初始化数据 new Student(){ StuID="1", StuAge=20, StuName="李白", StuSex="男", StuDesp="学生1", StuDate=DateTime.Now.ToString()}, new Student(){ StuID="2", StuAge=21, StuName="李明",StuSex="男",StuDesp="学生2",StuDate=DateTime.Now.AddDays(1).ToString() }, new Student(){StuID="3",StuAge=18,StuName="李丽",StuSex="女",StuDesp="学生3",StuDate=DateTime.Now.AddDays(2).ToString()}, new Student(){StuID="4",StuAge=27,StuName="韩梅",StuSex="女",StuDesp="学生4",StuDate=DateTime.Now.AddDays(-2).ToString()}, new Student(){StuID="5",StuAge=20,StuName="李磊",StuSex="男",StuDesp="学生5",StuDate=DateTime.Now.AddDays(-1).ToString()} }; return listStus; } public bool IsReusable { get { return false; } } #region Json序列化和反序列化操作 /// <summary> /// Json序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> private string JsonSerialize<T>(T t) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); jsonSerializer.WriteObject(ms, t); string json = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return json; } /// <summary> /// Json反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns></returns> private T JsonDeserialize<T>(string jsonString) { DataContractJsonSerializer jsonDeserializer = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)jsonDeserializer.ReadObject(ms); return obj; } #endregion } /// <summary> /// 学生类 /// </summary> public class Student { public string StuID; public string StuName; public int StuAge; public string StuSex; public string StuDesp; public string StuDate; } }
这个一般处理程序文件也包括对于Grid的分页处理的AJAX调用处理,下篇随笔将分享对于Grid如何进行数据分页的处理。