通常情况下,我们编写Extjs表格grid的时候,都是静态的,也就是说grid的表头、列都是固定的。在实际开发中,往往面对很多“非主流”的情况,就比如我曾经遇到的一个实际开发的案例,要求前台以Extjs Grid来显示数据库的表并进行编辑操作。数据库中有很多表,由于每张数据库表的字段数目是不同的,所以需要事先通过后台进行数据库表的字段计算,然后输出到前台给以显示。
还好这不是什么难事,因为Extjs的所有的配置格式基本上都是Json格式的,所有只要Grid的相关配置参数(如columnModel、fields)是Json格式的,那就不管是前台写死的还是后台动态输出的,都无关紧要。
1 protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
2 request.setCharacterEncoding("utf-8");
3 String gridJson = "{'action':true,'message':'error!',"
4 + "'data':["
5 + "{'number':'1','name': '张三','age': '21','edu': '家里蹲大学'},"
//这是加载的数据,其实可以从数据库中以分页取出
6 + "{'number':'2','name': '张四','age': '21','edu': '哈佛大学'},"
7 + "{'number':'3','name': '张五','age': '21','edu': '牛津大学'},"
8 + "{'number':'4','name': '张六','age': '21','edu': '昆明铁路中学'},"
9 + "{'number':'5','name': '大佬','age': '58','edu': '三年私塾'}"
10 + "],"
11 + "'columnModel':["
12 + "{'header': '编号','dataIndex': 'number','width':40},"
13 + "{'header': '姓名','dataIndex': 'name',editor:new Ext.grid.GridEditor(new Ext.form.NumberField())},"
14 + "{'header': '年龄','dataIndex': 'age'},"
15 + "{'header': '学历','dataIndex': 'edu'}"
16 + "],"
17 + "'fieldsNames':[{name:'number'},{name:'name'},{name:'age'},{name:'edu'}]"
18 + "}";
19 response.setContentType("application/json;charset=utf-8");
20 PrintWriter out = response.getWriter();
21 System.out.println(gridJson);
22 out.print(gridJson);
23 }
1 protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
2 request.setCharacterEncoding("utf-8");
3 String gridJson = "{'action':true,'message':'error!',"
4 + "'data':["
5 + "{'course':'人工智能','teacher': 'Tom'},"
//这是加载的数据,其实可以从数据库中以分页取出
6 + "{'course':'常微分','teacher': 'MR. Xu'},"
7 + "{'course':'武术','teacher': '王霸'},"
8 + "{'course':'天文常识','teacher': '尚文格'},"
9 + "{'course':'电子商务','teacher': '刘芳'},"
10 + "{'course':'数学分析','teacher': 'MR. Xu'},"
11 + "{'course':'大学生心理健康','teacher': '李四'}"
12 + "],"
13 + "'columnModel':["
14 + "{'header': '课程','dataIndex': 'course'},"
15 + "{'header': '授课教师','dataIndex': 'teacher'}"
16 + "],"
17 + "'fieldsNames':[{name:'course'},{name:'teacher'}]"
18 + "}";
19 response.setContentType("application/json;charset=utf-8");
20 PrintWriter out = response.getWriter();
21 System.out.println(gridJson);
22 out.print(gridJson);
23 }
为了更接近于实际开发,我们通常会把数据的查询和列的显示放在不同的控制器Servlet中进行处理,所以,可以让Extjs Ajax请求两个Servlet,让他们分别从数据库抓取数据和决定grid的显示策略。