Sigma Grid 純javascript,Sigma grid 用Ajax作grid展示並可實現數據的編輯,支持滾動表格及排序。它是很是強大的而且簡單易用而且能整合php,asp.net,jsp,RoR
研究版本:Sigma Grid 2.2
Grid目錄結構:
grid
|--->calendar
| |--calendar.js
| |--calendar-blue.css
| |--calendar-cn.js
| |--calendar-cn-utf8.js
| |--calendar-en.js
| |--calendar-setup.js
| |--simple-1.html
|--> flashchart
| |---->fusioncharts
| | |--->charts
| | | |--FCF_Area2D.swf
| | | |--略……(.swf)
| | |--ChangeDataXML.html
| | |--Chart.html
| | |--ChartChange.html
| | |--FusionCharts.js
|--->skin
| |---->china
| | |--->images
| | | |--cell_index_bg.gif
| | | |--略……(.gif)
| | |--skinstyle.css
| |---->default
| | |--->images
| | | |--button_bg.gif
| | | |-- 略……(.gif)
| | |--skinstyle.css
| |---->mac
| | |--->images
| | | |--button_bg.gif
| | | |-- 略……(.gif)
| | |--skinstyle.css
| |---->vista
| | |--->images
| | | |--cell_index_bg.gif
| | | |-- 略……(.gif)
| | |--skinstyle.css
|--gt_grid_all.js
|--gt_grid_height.css
|--gt_grid.css
|--gt_msg_en.js javascript
這裏以master/details和Sigma Grid CRUD爲例,說明Sigma Grid的使用方法,各個參數的做用,數據的傳輸,及數據的保存。
master/details的demo演示頁面爲example_master_details.html
此demo演示了父子關係的grid。子grid爲明細信息,經過鼠標點擊父grid的某條記錄關聯出子grid內容。
下面着重介紹此grid的使用方法:
首先在頁面中定義兩個grid的位置
php
- <div id="bigbox" style="margin:15px;display:!none;">
- <div id="gridbox" style="border:0px solid #cccccc;background-color:#f3f3f3;padding:5px;height:200px;width:700px;" ></div>
- </div>
- <div id="bigboxDetails" style="margin:15px;display:!none;">
- <div id="gridboxDetails" style="border:0px solid #cccccc;background-color:#f3f3f3;padding:5px;height:250px;width:700px;" ></div>
- </div>
自定義grid列頭
- <table id="myHead" style="display:none">
- <tr>
- <td rowspan="2" columnId='chk' resizable='false'>
- <input id="g1_chk" type="checkbox"/></td>
- <td rowspan="2" columnId='no' resizable='false'>Order No</td>
- <td rowspan="2" columnId='employee' resizable='false'>Employee</td>
- <td colspan="7">Order Info</td>
- </tr>
- <tr>
- <td columnId='country'>Country</td>
- <td columnId='customer'>Customer<img src="./images/customer.gif"/></td>
- <td columnId='bill2005'>2005</td>
- <td columnId='bill2006'>2006</td>
- <td columnId='bill2007'>2007</td>
- <td columnId='bill2008'>2008</td>
- <td columnId='orderDate'>Ship Date</td>
- </tr>
- </table>
//定義兩個grid
- var grid_demo_id = "myGrid1" ;
- var grid_details_id = "myGrid2";
構建父grid數據結構
- var dsOption= {
-
- fields :[
- {name : 'no' },
- {name : 'country' },
- {name : 'customer' },
- {name : 'employee' },
- {name : 'bill2005' ,type: 'float' },
- {name : 'bill2006' ,type: 'float' },
- {name : 'bill2007' ,type: 'float' },
- {name : 'bill2008' ,type: 'float' },
- {name : 'orderDate' ,type:'date' }
-
- ],
- uniqueField : 0 , //It could be unique field name or unique field index in fields
- recordType : 'object' //記錄類型只能是:'object' or 'array'
- }
構建子grid數據結構
- var dsOptionDetails= {
-
- fields :[
- {name : 'no' },
- {name : 'product' },
- {name : 'unitPrice' ,type:'float' },
- {name : 'quantity' ,type: 'int' },
- {name : 'discount' ,type: 'float' },
- {name : 'taxFree' ,type: 'int' },
- {name : 'taxRate' ,type: 'float' },
-
- {name : 'shipTo', type: 'int'},
- {name : 'shipment'},
- {name : 'note'},
-
- {name : 'tax',type: 'float' , initValue : function(record){
- var avg = record[5]*record[6];
- return avg.toFixed(2);
- }},
- {name : 'totalPrice' ,type: 'float' , initValue : function(record){
- var avg = record[2]*record[3]*record[4]*record[5]*record[6];
- return avg.toFixed(2);
- }}
- ],
-
- recordType : 'array'
- }
- //渲染成checked.gif
- function example_renderTaxFree(value ,record,columnObj,grid,colNo,rowNo){
- if(value==0) return "<img src='./images/unchecked.gif'>";
- return "<img src='./images/checked.gif'>";
-
- }
//渲染成星星 five_star
- function example_renderDiscount(value ,record,columnObj,grid,colNo,rowNo){
- var i = Math.round(value / 0.4 * 5);
- if(i>5)i=5;if(i<1)i=1;
- return "<IMG SRC=\"./images/five_star" + i + ".gif\" />"
-
-
- }
構建父grid 列樣式
/*
isCheckColumn:選項列
filterable:是否能夠過濾此列
exportable:輸出表格
id:id
header:顯示的名稱
width:寬度
inChart:是否在圖表中統計
chartColor:圖表顏色
*/
- var colsOption = [
- {id: 'chk' ,isCheckColumn : true, filterable: false, exportable:false},
- {id: 'no' , header: "Order No" , width :60 },
- {id: 'employee' , header: "Employee" , width :80 },
- {id: 'country' , header: "Country" , width :70 },
- {id: 'customer' , header: "Customer" , width :80 },
- {id: 'bill2005' , header: "2005" , width :60, inChart :true, chartColor : 'eecc99'},
- {id: 'bill2006' , header: "2006" , width :60, inChart :true, chartColor : '66eeaa' },
- {id: 'bill2007' , header: "2007" , width :60, inChart :true, chartColor : 'd65555' },
- {id: 'bill2008' , header: "2008" , width :60, inChart :true, chartColor : 'eeaa33' },
- {id: 'orderDate' , header: "Delivery Date" , width :100}
-
- ];
構建子grid 列樣式
/*
editor:能夠編輯此列 {type:類型
options:爲下拉列表提供數據
defaultText:默認值
validRule:驗證'R' - Required
'N' - Number
'E' - Email
'F' - Float}
frozen:是否鎖定此列 若是被鎖定 在拖動滾動條時候此列不會發生變化
sortOrder:排序 asc 或 desc
renderer:渲染效果 參數爲function(value ,record,colObj,grid,colNo,rowNo)
align:位置
*/
- var colsOptionDetails = [
- {id: 'no' , header: "Item No" , width :60 , editor:{type:"text"},
- frozen : true},
- {id: 'product' , header: "Product" , width :100,
- grouped : true , frozen : true , sortOrder : 'asc',
- editor : { type :"select" ,
- options : {"Abalone":"Abalone","Amber":"Amber","Amethyst":"Amethyst","Aquamarine":"Aquamarine",
- "Cameos":"Cameos","Citrine":"Citrine","Coral":"Coral","Crystal":"Crystal","Cubic Zirconia":"Cubic Zirconia",
- "Emerald":"Emerald","Enamel":"Enamel","Garnet":"Garnet","Glass":"Glass","Moissanite":"Moissanite",
- "Onyx":"Onyx","Opal":"Opal","Pearl":"Pearl"} ,defaultText : '' }},
- {id: 'unitPrice' , header: "Unit Price" , width :60 ,
- editor: { type :"text" ,validRule : ['R','F'] } },
- {id: 'quantity' , header: "Quantity" , width :80,
- editor: { type :"text" ,validRule : ['R'] } },
- {id: 'discount' , header: "Discount" , width :100 ,renderer : example_renderDiscount,
- editor: { type :"text" ,validRule : ['R','F'] } },
-
- {id: 'taxFree' , header: "Tax Free" , width :60 ,renderer : example_renderTaxFree },
- {id: 'taxRate' , header: "Tax Rate" , width :60 ,
- editor: { type :"text" ,validRule : ['R','F'] } },
- {id: 'tax' , header: "Tax" , width :60},
- {id: 'totalPrice' , header: "Total Price" , width :60, align:"right"
- },
- {id: 'shipTo' , header: "Ship To" , width :100 },
- {id: 'shipment' , header: "Shipment" , width :100 },
- {id: 'note' , header: "Note" , width :150 }
-
- ];
父grid屬性
/*
width:寬度
height:高度
container:grid建立的位置
dataset:數據
columns:列樣式
pageSizeList:頁面顯示條數
customHead:自定義grid頭
onClickCell:點擊觸發事件
SigmaGridPath:未知
loadURL:獲取數據地址
exportURL:輸出地址 用於輸出EXCEL XML CSV PDF
exportFileName:輸出名稱
remotePaging:指定服務器端不分頁工做
defaultRecord:當點擊添加按鈕時默認的加入一行的數據
pageSize:頁面顯示記錄數
toolbarContent:grid 工具條{
nav goto - 分頁
pagesize - 顯示記錄數
reload - 刷新
print - 打印
csv - 輸出CSV格式文件
xls - 輸出xls格式文件
pdf - 輸出pdf格式文件
filter - 過濾查詢
chart - 圖表
state - 狀態
}
*/
- var gridOption={
- id : grid_demo_id,
- width: "700",
- height: "350",
- container : 'gridbox',
- replaceContainer : true,
- dataset : dsOption ,
- columns : colsOption ,
- pageSizeList : [5,10,15,20],
- customHead : 'myHead',
- onClickCell : function(value, record , cell, row, colNO, rowNO,columnObj,grid){
- var no = record["no"]>"070-19"?"070-19":record["no"];
- var grid=Sigma.$grid(grid_details_id);
- grid.loadURL = "./data/" + no + ".js";
- grid.reload();
- },
- SigmaGridPath : '../grid/',
- loadURL : 'test.jsp?actionMethod=list',
- saveURL : 'test.jsp?actionMethod=save' ,
- exportURL : './export_php/testMasterList.php?export=true',
- exportFileName : 'Sales Master Report',
- remotePaging : false,
- defaultRecord : ["","","","",0,0,0,0,"2008-01-01"],
- pageSize:20,
- toolbarContent : 'nav goto | pagesize | reload | print csv xls xml pdf filter chart | state'
- };
子grid屬性
/*
editable:表格是否可編輯
groupable:true分組菜單將會出如今主菜單中,而且啓動分組功能
clickStartEdit:點擊鼠標出發編輯事件
showGridMenu:是否顯示主菜單
allowCustomSkin:是否制定skin出如今菜單上
allowFreeze:是否被凍結欄出如今主菜單
allowHide:隱藏是否出如今主菜單
allowGroup:組是否出如今主菜單
*/
- var gridOptionDetails={
- id : grid_details_id,
- loadUrl : './data/010-0.js',
- saveURL : 'test.jsp?actionMethod=save' ,
- width: "700",
- height: "260",
- container : 'gridboxDetails',
- replaceContainer : true,
- editable : true,
- groupable : true,
- pageSizeList : [5,10,15,20],
- dataset : dsOptionDetails ,
- columns : colsOptionDetails ,
- clickStartEdit : true ,
- defaultRecord : ["","",0,0,0.0,0,0.0,"Customer","UPS",""],
- pageSize:30,
- toolbarContent : 'reload | add del save | print | state',
- showGridMenu : true,
- allowCustomSkin : true ,
- allowFreeze : true ,
- allowHide : true ,
- allowGroup : true,
- customRowAttribute : function(record,rn,grid){
- if (record[11]>80){
- return 'style="height:50px; background-color:#ffddcc"';
- }
- }
- };
建立Grid對象並輸出
- var mygrid=new Sigma.Grid( gridOption );
- var mygridDetails = new Sigma.Grid(gridOptionDetails);
-
- Sigma.Util.onLoad( Sigma.Grid.render(mygrid) );
- Sigma.Util.onLoad( Sigma.Grid.render(mygridDetails) );
Sigma Grid CRUD的demo演示頁面爲list1.jsp
此例子用來講明 先後臺的數據交互 及grid的增刪改查及保存功能
獲取數據屬性:
loadURL
保存數據屬性:
saveURL
例:
loadURL : APP_PATH+'/views/controller.jsp?actionMethod=list'
saveURL : APP_PATH+'/views/controller.jsp?actionMethod=save'
這裏爲了實現功能效果只簡單的使用jsp直接訪問數據庫實現查詢CRUD的工做。
固然也使用MVC結構來實現,只要返回的數據類型是JOSN而且符合Sigma Grid的數據格式便可
controller.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ page import="java.sql.*,java.util.*"%>
- <%@ page import="com.fins.gt.server.*"%>
- <%!
- Connection getConnection(){
-
- String url="jdbc:mysql://localhost:3306/sigma_grid_server";
- Connection conn= null;
- try{
- Class.forName("com.mysql.jdbc.Driver").newInstance();
- conn = DriverManager.getConnection(url,"root","");
- }catch(Exception e){
-
- }
- return conn;
- }
-
- void closeConnection(Connection conn){
- try{
- conn.close();
- }catch(Exception e){
-
- }
- }
-
-
- List listOrders(){
- Connection conn = getConnection();
- if(conn==null)
- return new ArrayList();
- Statement stmt = null;
-
- ResultSet rs = null;
- List list = new ArrayList();
-
- try{
- stmt = conn.createStatement();
- rs = stmt.executeQuery("select * from orders");
- while(rs.next()){
- Map map = new HashMap();
- map.put("order_no",new Long(rs.getLong("order_no")));
- map.put("employee",rs.getString("employee"));
- map.put("country",rs.getString("country"));
- map.put("customer",rs.getString("customer"));
- map.put("order2005",new Float(rs.getFloat("order2005")));
- map.put("order2006",new Float(rs.getFloat("order2006")));
- map.put("order2007",new Float(rs.getFloat("order2007")));
- map.put("order2008",new Float(rs.getFloat("order2008")));
- map.put("delivery_date",rs.getString("delivery_date"));
- list.add(map);
- }
- rs.close();
- stmt.close();
- }catch(Exception e){
- }
- closeConnection(conn);
- return list;
- }
-
- int[] insertOrders( List updatedList){
-
- int[] opresults=null;
- String sql="INSERT INTO orders (employee,country,customer,order2005,order2006,order2007,order2008,delivery_date) VALUES (?,?,?,?,?,?,?,?)";
- Connection conn=null;
- PreparedStatement pstmt = null;
- try {
- conn = getConnection();
- pstmt = conn.prepareStatement(sql);
- for (int i=;i<updatedList.size();i++){
- Map record= (Map)updatedList.get(i);
- pstmt.setString(1,String.valueOf(record.get("employee")));
- pstmt.setString(2,String.valueOf(record.get("country")));
- pstmt.setString(3,String.valueOf(record.get("customer")));
- pstmt.setString(4,String.valueOf(record.get("order2005")));
- pstmt.setString(5,String.valueOf(record.get("order2006")));
- pstmt.setString(6,String.valueOf(record.get("order2007")));
- pstmt.setString(7,String.valueOf(record.get("order2008")));
- pstmt.setString(8,String.valueOf(record.get("delivery_date")));
- pstmt.addBatch();
- }
- opresults = pstmt.executeBatch();
- } catch (SQLException e) {
- opresults=null;
- }finally{
- closeConnection(conn);
- }
- return opresults;
- }
-
- int[] updateOrders( List updatedList){
-
- int[] opresults=null;
- String sql="UPDATE orders SET customer=?, order2008=?, delivery_date=? WHERE order_no= ? ";
- Connection conn=null;
- PreparedStatement pstmt = null;
- try {
- conn = getConnection();
- pstmt = conn.prepareStatement(sql);
- for (int i=;i<updatedList.size();i++){
- Map record= (Map)updatedList.get(i);
- pstmt.setString(1,String.valueOf(record.get("customer")));
- pstmt.setString(2,String.valueOf(record.get("order2008")));
- pstmt.setString(3,String.valueOf(record.get("delivery_date")));
- pstmt.setString(4,String.valueOf(record.get("order_no")));
- pstmt.addBatch();
- }
- opresults = pstmt.executeBatch();
- } catch (SQLException e) {
- opresults=null;
- }finally{
- closeConnection(conn);
- }
- return opresults;
- }
-
-
- int[] deleteOrders( List updatedList){
-
- int[] opresults=null;
- String sql="DELETE FROM orders WHERE order_no= ? ";
- Connection conn=null;
- PreparedStatement pstmt = null;
- try {
- conn = getConnection();
- pstmt = conn.prepareStatement(sql);
- for (int i=;i<updatedList.size();i++){
- Map record= (Map)updatedList.get(i);
- pstmt.setString(1,String.valueOf(record.get("order_no")));
- pstmt.addBatch();
- }
- opresults = pstmt.executeBatch();
- } catch (SQLException e) {
- opresults=null;
- }finally{
- closeConnection(conn);
- }
- return opresults;
- }
-
- boolean saveOrders(List insertedRecords , List updatedList, List deletedRecords){
- //you can control transaction, commit, rollback here
- int[] insertCodes = insertOrders(insertedRecords);
- int[] updateCodes = updateOrders(updatedList);
- int[] deleteCodes = deleteOrders(deletedRecords);
- boolean success=insertCodes!=null && updateCodes!=null && deleteCodes!=null;
- return success;
- }
-
- %>
- <%
-
- // GridServerHandler is server side wrapper, you can get all the info posted to server in your Java way instead of JavaScript
- GridServerHandler gridServerHandler=new GridServerHandler(request,response);
-
- String operation = request.getParameter("actionMethod");
- if("save".equals(operation)){
- System.out.println("----save-----");
- boolean success=true;
-
- //取得新增的數據集合, 每條數據記錄在 map 裏
- List insertedRecords = gridServerHandler.getInsertedRecords();
- //取得修改的數據集合, 每條數據記錄在 map 裏
- List updatedList = gridServerHandler.getUpdatedRecords();
- //取得刪除的數據集合, 每條數據記錄在 map 裏
- List deletedRecords = gridServerHandler.getDeletedRecords();
-
-
- // 若是但願取得bean的集合 那麼請使用有參方法: xxx.getXXXXXXRecords(Class beanClass);
- //例如: List updateList = gridServerHandler.getUpdatedRecords(StudentVO.class);
-
- //調用"相應的方法" 來update delete insert數據
- success = saveOrders(insertedRecords , updatedList, deletedRecords );
-
-
- //設置該次操做是否成功.
- gridServerHandler.setSuccess(success);
-
- //若是操做不成功 你也能夠自定義一些異常信息發送給客戶端.
- // gridServerHandler.setSuccess(false);
- // gridServerHandler.setException("... exception info ...");
-
- //向客戶端輸出json字符串.
- out.print(gridServerHandler.getSaveResponseText());
-
- }else { //client is retrieving data
- List list = listOrders();
- System.out.println("----list-----");
-
- int totalRowNum= list.size();
- // 取得總記錄數
- gridServerHandler.setTotalRowNum(totalRowNum);
-
- //調用"相應的方法" 來取得數據.下面4個方法 一般對於進行分頁查詢頗有幫助,根據須要使用便可.
- // gridServerHandler.getStartRowNum() 當前頁起始行號
- // gridServerHandler.getEndRowNum() 當前頁結束行號
- // gridServerHandler.getPageSize() 每頁大小
- // gridServerHandler.getTotalRowNum() 記錄總條數
-
-
- // 本例中list裏的元素是 map,
- // 若是元素是bean, 請使用 gridServerHelp.setData(list,BeanClass.class);
- gridServerHandler.setData(list);
- // gridServerHandler.setException("your exception message");
-
- //向客戶端輸出json字符串.
- out.print(gridServerHandler.getLoadResponseText());
- System.out.print(gridServerHandler.getLoadResponseText());
- // 你也能夠 使用 gridServerHandler.getLoadResponseText() 來取得字符串.
- // 而後自行向 客戶端輸出, 這樣作的好處是 你能夠本身來決定response的contentType和編碼.
-
-
- }
- %>
經過上面的代碼能夠看出 操做grid的對象是GridServerHandler
使用GridServerHandler對象,來操做grid中的數據。
上傳了demo,部署後訪問demo地址爲: http://localhost:8080/GtGridDemo/views/demo1.jsp .................................................................demo2.html .................................................................demo3.jsp .................................................................demo4.html .................................................................demo5.html 經過以上demo實現如下功能 簡單載入一個結果集(select top 20 * from Orders),主要展現如下特色(如何load數據,如何鎖定表頭列頭,跨列表頭如何設定,如何設定客戶端按列排序) 帶2個條件查詢Orders表(如何傳入查詢條件查詢), 主從表的載入(orders, Order Details) 能夠的編輯單表Grid(單元格的編輯框如何定義,如何add和delete一行,編輯後的數據如何提交給jsp) 能夠的編輯主從表Grid(重點體現子表如何編輯,並保持主記錄和子記錄的關係,編輯後的數據如何提交給jsp) 打印功能的實現(pdf,excel,)