ExtJS EditorGridPanel 示例之JSON格式Store前后台增删改查

json格式传递数据示例,入口html页面:

[xhtml]  view plain copy print ?
  1. >  
  2. <html>  
  3.     <head>  
  4.     <title>用户数据编辑 用JsonReader 实现分页title>  
  5.     <meta http-equiv="Content-Type" content="text/html; charset=gbk" />  
  6.     <meta http-equiv="author" content="hoojo">  
  7.     <meta http-equiv="email" content="[email protected]">  
  8.     <meta http-equiv="blog" content="http://blog.csdn.net/IBM_hoojo">   
  9.     <link rel="stylesheet" type="text/css" href="../ext2/resources/css/ext-all.css">link>  
  10.     <script type="text/javascript" src="../ext2/adapter/ext/ext-base.js">script>  
  11.     <script type="text/javascript" src="../ext2/ext-all.js">script>  
  12.     <script type="text/javascript" src="../ext2/build/locale/ext-lang-zh_CN-min.js">script>  
  13.     <script type="text/javascript" src="JsonPagingEditorGridPanel.js">script>  
  14.     <script type="text/javascript">         
  15.         Ext.onReady(function (){  
  16.             Ext.QuickTips.init();  
  17.             //Ext.form.Field.prototype.msgTarget = "side";  
  18.               
  19.             Ext.BLANK_IMAGE_URL = "../ext2/resources/images/default/s.gif";  
  20.             new JsonPagingEditorGridPanel();  
  21.         });  
  22.     script>  
  23.     head>  
  24.     <body>  
  25.   
  26.     body>  
  27. html>  

 

JsonPagingEditorGridPanel.js:

[javascript]  view plain copy print ?
  1. /** 
  2.  * 用JSON格式的数据形式:Ext.data.Store,Ext.data.JsonReader解析器,实现editorGrid的增删改查 
  3.  * author: hoojo 
  4.  * email: [email protected] 
  5.  * blog: http://blog.csdn.net/IBM_hoojo 
  6.  * ext-lib: v2.2 
  7.  */  
  8. /****************************************************************/  
  9.                     /*******JsonPagingEditorGridPanel*******/  
  10. /****************************************************************/  
  11. JsonPagingEditorGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {  
  12.     sexCombo: null,  
  13.     inserted: [],  
  14.     constructor: function () {  
  15.       
  16.         this.sexCombo = new Ext.form.ComboBox({  
  17.             mode: "local",  
  18.             value: "全部",  
  19.             readOnly: true,  
  20.             triggerAction: "all",  
  21.             displayField: "sex",  
  22.             //listAlign : "bl-tl", //下拉列表的显示方式 bl-tl是在上方显示,相反tl-bl是从下方显示  
  23.             store: new Ext.data.SimpleStore({  
  24.                 data: ["男""女""全部"],  
  25.                 expandData: true,  
  26.                 fields: ["sex"]  
  27.             }),  
  28.             listeners: {  
  29.                 "select": {  
  30.                     fn: this.filterSex,  
  31.                     scope: this  
  32.                 }  
  33.             }  
  34.         });  
  35.           
  36.         this["store"] = new Ext.data.Store({  
  37.             url: JsonPagingEditorGridPanel.USER_STORE_URL,  
  38.             reader: new Ext.data.JsonReader({  
  39.                     id: "id"//维护当前数据的唯一性(和数据库主键类似,避免数据重复--过滤重复数据)  
  40.                     root: "users",  
  41.                     totalProperty: "totals"  
  42.                 },  
  43.                 Ext.data.Record.create(["id","name",   
  44.                     {name: "age", type: "int"}, "sex",   
  45.                     {name: "birthday", type: "date", dateFormat: "Y-m-d"}  
  46.                 ])  
  47.             ),  
  48.             sortInfo:{field:"id", direction:"ASC"//排序  
  49.         });  
  50.           
  51.         JsonPagingEditorGridPanel.superclass.constructor.call(this, {  
  52.             renderTo: Ext.getBody(),  
  53.             width: 480,  
  54.             height: 300,  
  55.             frame: true,  
  56.             //loadMask:true, //显示加载旋转条  
  57.             stripeRows: true//隔行变色,区分表格行  
  58.             clicksToEdit: 2, //表示点击多少次数才可以编辑表格  
  59.             collapsible: true//是否在右上角显示收缩按钮  
  60.             animCollapse: true//表示收缩(闭合)面板时,显示动画效果  
  61.             trackMouseOver: true//鼠标在行上移动时显示高亮  
  62.             enableColumnMove: false,//禁止用户拖动表头  
  63.             //disableSelection:true,  
  64.             autoExpandColumn: "name"//这里指定的name的id ,此属性可以根据当前列 填充空白区域  
  65.             title: "用户数据编辑器",             
  66.             tbar: [  
  67.                 "->","查看方式:",  
  68.                 this.sexCombo,  
  69.                 {  
  70.                     text: "添加数据",  
  71.                     handler: this.onAddClick,  
  72.                     scope: this  
  73.                 },"-",{  
  74.                     text: "删除数据",  
  75.                     handler: this.onRemoveClick,  
  76.                     scope: this  
  77.                 },"-",{  
  78.                     text: "保存数据",                     
  79.                     handler: this.onCommitStore,  
  80.                     scope: this  
  81.                 }  
  82.             ],  
  83.             bbar: new Ext.PagingToolbar({  
  84.                 //width: 480, //如果pagingToolbar不在bbar[]括号中就不需要width,否则就要指定宽度才能显示displayInfo  
  85.                 pageSize: 5,  
  86.                 store: this.store,  
  87.                 displayInfo: true,  
  88.                 displayMsg: "显示第{0}-{1}条,共有{2}条记录",  
  89.                 emptyMsg: "没有记录"  
  90.             }),  
  91.             columns:[{  
  92.                 id: "name",  
  93.                 header: "姓名",  
  94.                 align: "center",  
  95.                 dataIndex: "name",  
  96.                 editor: new Ext.form.TextField({  
  97.                     allowBlank: false,  
  98.                     blankText: "姓名不能为空,必须输入"  
  99.                 })  
  100.             },{  
  101.                 header: "年龄",  
  102.                 align: "center",  
  103.                 dataIndex: "age",  
  104.                 editor: new Ext.form.NumberField({  
  105.                     allowBlank: false,  
  106.                     allowNegative: false//只能为正数  
  107.                     //maxValue: 1000000000,  
  108.                     grow: true//前半部分显示正在改的数据,后半部分显示以前的老数据  
  109.                     selectOnFocus: true//当获得焦点时,选中所有的文本内容  
  110.                     minValue: 1  
  111.                 })  
  112.             },{  
  113.                 header: "性别",  
  114.                 align: "center",  
  115.                 dataIndex: "sex",  
  116.                 editor: new Ext.form.ComboBox({  
  117.                     mode: "local",                    
  118.                     value: "男",  
  119.                     readOnly: true,  
  120.                     displayField: "sex",  
  121.                     triggerAction: "all",                                         
  122.                     store: new Ext.data.SimpleStore({  
  123.                         data: ["男""女"],  
  124.                         expandData: true,  
  125.                         fields: ["sex"]  
  126.                     })  
  127.                 })  
  128.             },{  
  129.                 header: "生日",  
  130.                 align: "center",  
  131.                 sortable: true,  
  132.                 dataIndex: "birthday",  
  133.                 renderer: Ext.util.Format.dateRenderer('Y-m-d'),  
  134.                 editor: new Ext.form.DateField({  
  135.                     format: "Y-m-d",  
  136.                     minValue: "1950-01-01",  
  137.                     disabledDays: [0, 7],//datefield的第0列:周日和第7列:周六不能编辑  
  138.                     disabledDaysText: "周末不能选择"  
  139.                 })  
  140.             }],  
  141.             sm: new Ext.grid.RowSelectionModel({  
  142.                 singleSelect: true  
  143.             })  
  144.               
  145.         });  
  146.         this.store.load({params: {start: 0, limit: 5}});  
  147.         Ext.Ajax.on("requestcomplete"function (conn, response, options) {  
  148.             //alert(response.responseText);  
  149.             Ext.example.msg('Click','You clicked on "Action 1".');  
  150.   
  151.         });  
  152.     },  
  153.     filterSex: function (cob) {  
  154.         if (cob.getValue() == "全部"){  
  155.             this.store.clearFilter();  
  156.         }  
  157.         else  
  158.             this.store.filter("sex", cob.value);  
  159.     },  
  160.     onAddClick: function () {  
  161.         var rs = new Ext.data.Record({id: "",name: "", age: 1, sex: "", birthday: 0000-00-00});  
  162.         this.getStore().add(rs);  
  163.         rs.set("name""ext");  
  164.         rs.set("age", 22);  
  165.         rs.set("sex""男");  
  166.         rs.set("birthday"new Date());  
  167.         this.inserted.push(rs);  
  168.         this.startEditing(this.store.getCount() - 1, 0);  
  169.     },  
  170.     saveInsertData: function (conn, response) {  
  171.         var xml = response.responseXML;  
  172.         var root = xml.documentElement;  
  173.         for (var i = 0; i < root.childNodes.length; i++) {  
  174.             this.inserted[i].set("id", root.childNodes[i].text);  
  175.         }  
  176.         this.getStore().commitChanges();  
  177.         this.inserted = [];  
  178.     },  
  179.     onCommitStore: function () {  
  180.         var mf = this.getStore().modified;  
  181.         var temp = [];  
  182.         for (var i = 0; i < mf.length; i ++) {  
  183.             if (mf[i].get("id") == ""){  
  184.                 continue;  
  185.             }  
  186.             var data = {};  
  187.             for (var j in mf[i].modified) {  
  188.                 data[j] = mf[i].get(j);  
  189.             }  
  190.             temp.push(Ext.apply(data, {id: mf[i].get("id")}));            
  191.         }  
  192.           
  193.         for (var i = 0; i < this.inserted.length; i ++) {  
  194.             temp.push(this.inserted[i].data);  
  195.         }  
  196.         Ext.Ajax.on("requestcomplete"function (conn, response, options) {  
  197.             alert(response.responseText);  
  198.         });  
  199.         //Ext.Ajax.on("requestcomplete", this.saveInsertData, this);  
  200.         //想服务器发送请求,传递修改的数据(只含修改的数据)  
  201.         Ext.Ajax.request({url: "../ServiceServlet?method=edit", params: {content:Ext.util.JSON.encode(temp)}});  
  202.         this.store.commitChanges();       
  203.         this.filterSex(this.sexCombo);  
  204.     },  
  205.     onRemoveClick: function () {  
  206.         var rs = this.getSelectionModel();  
  207.         try{  
  208.             if (rs.getCount() == 0) {  
  209.                 Ext.Msg.alert("系统提示""没有选定数据,请选择数据行!");  
  210.                   
  211.             }else {  
  212.                 Ext.Msg.confirm("系统提示""您确定要删除当前数据吗?"this.removeUserInfo, this);  
  213.             }  
  214.         }catch(er) {  
  215.             Ext.Msg.alert("系统提示", er.discription);  
  216.         }  
  217.     },  
  218.     removeUserInfo: function (btnText) {  
  219.         if (btnText == "yes"){  
  220.             var rs = this.getSelectionModel().getSelected();  
  221.             this.getStore().remove(rs);  
  222.               
  223.             if (rs.get("id") != "") {  
  224.                 Ext.Ajax.on("requestcomplete"function (conn, response, options) {  
  225.                     if (response.responseText == "success") {  
  226.                         alert("success");  
  227.                     }else {  
  228.                         alert("failure");  
  229.                     }  
  230.                 });  
  231.                 Ext.Ajax.request({url: "../ServiceServlet?method=remove", params: {id:rs.get("id")}});  
  232.             }else {               
  233.                 this.inserted.remove(rs);  
  234.                 //this.getStore().modified.romove(rs);  
  235.             }  
  236.         }  
  237.     }  
  238.       
  239. });  
  240. JsonPagingEditorGridPanel.USER_STORE_URL = "http://localhost:8080/Demo3/ServiceServlet?method=json";  

 

后台java code:

[java]  view plain copy print ?
  1. import java.io.PrintWriter;  
  2. import java.util.List;  
  3. import javax.servlet.ServletException;  
  4. import javax.servlet.http.HttpServlet;  
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7. import com.hoo.dao.IUser;  
  8. import com.hoo.dao.impl.UserDao;  
  9. import com.hoo.entity.UserInfo;  
  10.   
  11. @SuppressWarnings({"unchecked""serial"})  
  12. public class ServiceServlet extends HttpServlet {  
  13.       
  14.     private IUser dao = new UserDao();  
  15.       
  16.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  17.             throws ServletException, IOException {  
  18.         response.setCharacterEncoding("GBK");  
  19.           
  20.         PrintWriter out = response.getWriter();  
  21.           
  22.         StringBuilder builder = new StringBuilder();  
  23.         String method = request.getParameter("method");   
  24.         if ("json".equals(method)) {  
  25.             int start = Integer.parseInt(request.getParameter("start"));  
  26.             int limit = Integer.parseInt(request.getParameter("limit"));  
  27.               
  28.             Object[] obj = dao.loadUserInfo(start, limit);  
  29.             List list = (List) obj[1];  
  30.               
  31.             builder.append("{totals:").append(obj[0]).append(",users:[");  
  32.             for (int i = 0; i < list.size(); i++) {  
  33.                 UserInfo u = (UserInfo) list.get(i);  
  34.                 builder.append("{id:/"").append(u.getId())  
  35.                 .append("/",name:/"").append(u.getName())                 
  36.                 .append("/",age:").append(u.getAge())  
  37.                 .append(",sex:/"").append(u.getSex())  
  38.                 .append("/",birthday:/"").append(u.getBirthday())  
  39.                 .append("/"}");  
  40.                 if (i < list.size()-1) {  
  41.                     builder.append(",");  
  42.                 }  
  43.             }  
  44.             builder.append("]}");  
  45.               
  46.             out.write(builder.toString());  
  47.         }  
  48.         if ("edit".equals(method)) {  
  49.             String content = request.getParameter("content");  
  50.               
  51.             out.print(content);  
  52.         }  
  53.           
  54.         if ("remove".equals(method)) {  
  55.             Integer id = Integer.parseInt(request.getParameter("id"));  
  56.             if (dao.removeUserInfo(id)) {  
  57.                 out.print("success");  
  58.             }else {  
  59.                 out.print("failure");  
  60.             }  
  61.         }  
  62.         out.flush();  
  63.         out.close();  
  64.     }  
  65.   
  66.       
  67.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  68.             throws ServletException, IOException {  
  69.         this.doGet(request, response);  
  70.     }  
  71.   
  72. }  

 

 

至此,ExtJS中常用的3中交互方式的示例全部在此。其中json格式交互方式最为常用。

原因是xml格式体积过于庞大,里面有标签过多。而array数组格式的文件,虽然提交很小。

传输速度快。但在数据量很大的情况下,数据的可读性几乎全无。后来出现了json,

它简化了xml文件提交庞大的问题,可读性也非常好、在网络中的传输速度也很快,且易于使用、学习。

你可能感兴趣的:(【extjs】)