一、利用jQuery EasyUI的DataGrid創建CRUD應用
對網頁應用程序來說,正確采集和管理數據通常很有必要,DataGrid的CRUD功能允許我們創建頁面來列表顯示和編輯數據庫記錄。本教程將教會你如何運用jQuery EasyUI框架來實現DataGrid的CRUD功能 。
我們會用到如下插件:
· datagrid: 列表顯示數據。
· dialog: 增加或編輯單個用戶信息。
· form: 用來提交表單數據。
· messager: 用來顯示操作信息。
第一步:准備數據庫
使用MySql數據庫來保存用戶信息,並創建數據庫和“users”表。
第二步:創建DataGrid數據表格來顯示用戶信息
不需要編寫任何javascript代碼創建DataGrid數據表格。
- <table id="dg" title="My Users" class="easyui-datagrid" style="width:550px;height:250px"
- url="get_users.php"
- toolbar="#toolbar"
- rownumbers="true" fitColumns="true" singleSelect="true">
- <thead>
- <tr>
- <th field="firstname" width="50">First Name</th>
- <th field="lastname" width="50">Last Name</th>
- <th field="phone" width="50">Phone</th>
- <th field="email" width="50">Email</th>
- </tr>
- </thead>
- </table>
- <div id="toolbar">
- <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">Remove User</a>
- </div>
如下圖所示,我們不需要寫任何一行javascript代碼:
DataGrid使用“url”屬性來指定“get_users.php”,用來從服務器端接收數據。
get_users.php代碼文件:
- $rs = mysql_query('select * from users');
- $result = array();
- while($row = mysql_fetch_object($rs)){
- array_push($result, $row);
- }
- echo json_encode($result);
第三步:創建表單對話框
增加或者編輯用戶信息,我們使用同一對話框。
- <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px" closed="true" buttons="#dlg-buttons">
- <div class="ftitle">User Information</div>
- <form id="fm" method="post">
- <div class="fitem">
- <label>First Name:</label>
- <input name="firstname" class="easyui-validatebox" required="true">
- </div>
- <div class="fitem">
- <label>Last Name:</label>
- <input name="lastname" class="easyui-validatebox" required="true">
- </div>
- <div class="fitem">
- <label>Phone:</label>
- <input name="phone">
- </div>
- <div class="fitem">
- <label>Email:</label>
- <input name="email" class="easyui-validatebox" validType="email">
- </div>
- </form>
- </div>
- <div id="dlg-buttons">
- <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">Cancel</a>
- </div>
對話框的創建也不需要編寫javascript代碼。
第四步:實現增加和編輯用戶功能
增加用戶信息時,打開對話框,清除表單數據。
- function newUser(){
- $('#dlg').dialog('open').dialog('setTitle','New User');
- $('#fm').form('clear');
- url = 'save_user.php';
- }
編輯用戶信息時,打開對話框,將選擇的數據表格行數據裝入表單。
- var row = $('#dg').datagrid('getSelected');
- if (row){
- $('#dlg').dialog('open').dialog('setTitle','Edit User');
- $('#fm').form('load',row);
- url = 'update_user.php?id='+row.id;
- }
“url”保存URL地址,當保存用戶數據時,表單用它來提交(post)數據到服務器。
第五步:保存用戶數據
使用如下代碼來保存用戶數據:
- function saveUser(){
- $('#fm').form('submit',{
- url: url,
- onSubmit: function(){
- return $(this).form('validate');
- },
- success: function(result){
- var result = eval('('+result+')');
- if (result.errorMsg){
- $.messager.show({
- title: 'Error',
- msg: result.errorMsg
- });
- } else {
- $('#dlg').dialog('close'); // close the dialog
- $('#dg').datagrid('reload'); // reload the user data
- }
- }
- });
- }
提交表單前,“onSubmit”函數被調用,此時可校驗表單字段值。當表單字段值提交成功,關閉對話框和刷新數據表格數據。
第六步:刪除用戶
用如下代碼來刪除用戶:
- function destroyUser(){
- var row = $('#dg').datagrid('getSelected');
- if (row){
- $.messager.confirm('Confirm','Are you sure you want to destroy this user?',function(r){
- if (r){
- $.post('destroy_user.php',{id:row.id},function(result){
- if (result.success){
- $('#dg').datagrid('reload'); // 刷新用戶數據
- } else {
- $.messager.show({ // 顯示錯誤信息
- title: 'Error',
- msg: result.errorMsg
- });
- }
- },'json');
- }
- });
- }
- }
刪除一行數據時,會彈出一個confirm對話框來讓我們選擇確定是否真的刪除數據行。當刪除數據成功,調用“reload”方法刷新datagrid數據。
二、DataGrid的擴展應用
上一份教程我們創建的一個CRUD應用是使用對話框組件來增加或編輯用戶信息。本教程將教你如何創建一個CRUD 數據表格(datagrid). 為了讓這些CRUD功能正常工作,我們會用到edatagrid.js插件。
第一步:在HTML標識里定義DataGrid
- <table id="dg" title="My Users" style="width:550px;height:250px"
- toolbar="#toolbar" idField="id"
- rownumbers="true" fitColumns="true" singleSelect="true">
- <thead>
- <tr>
- <th field="firstname" width="50" editor="{type:'validatebox',options:{required:true}}">First Name</th>
- <th field="lastname" width="50" editor="{type:'validatebox',options:{required:true}}">Last Name</th>
- <th field="phone" width="50" editor="text">Phone</th>
- <th field="email" width="50" editor="{type:'validatebox',options:{validType:'email'}}">Email</th>
- </tr>
- </thead>
- </table>
- <div id="toolbar">
- <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:$('#dg').edatagrid('addRow')">New</a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="javascript:$('#dg').edatagrid('destroyRow')">Destroy</a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="javascript:$('#dg').edatagrid('saveRow')">Save</a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-undo" plain="true" onclick="javascript:$('#dg').edatagrid('cancelRow')">Cancel</a>
- </div>
第二步:使DataGrid可編輯
- $('#dg').edatagrid({
- url: 'get_users.php',
- saveUrl: 'save_user.php',
- updateUrl: 'update_user.php',
- destroyUrl: 'destroy_user.php'
- });
為可編輯的datagrid提供了“url”、“saveUrl”、“updateUrl”、“destroyUrl”屬性:
url: 從服務器端接收用戶數據。
saveUrl: 保存新用戶數據。
updateUrl: 更新現有用戶數據。
destroyUrl: 刪除現有用戶數據。
第三步:編寫服務器端處理代碼
保存新用戶(save_user.php):
- $firstname = $_REQUEST['firstname'];
- $lastname = $_REQUEST['lastname'];
- $phone = $_REQUEST['phone'];
- $email = $_REQUEST['email'];
- include 'conn.php';
- $sql = "insert into users(firstname,lastname,phone,email) values('$firstname','$lastname','$phone','$email')";
- @mysql_query($sql);
- echo json_encode(array(
- 'id' => mysql_insert_id(),
- 'firstname' => $firstname,
- 'lastname' => $lastname,
- 'phone' => $phone,
- 'email' => $email
- ));
更新現有用戶(update_user.php):
- $id = intval($_REQUEST['id']);
- $firstname = $_REQUEST['firstname'];
- $lastname = $_REQUEST['lastname'];
- $phone = $_REQUEST['phone'];
- $email = $_REQUEST['email'];
- include 'conn.php';
- $sql="update users set firstname='$firstname',lastname='$lastname',phone='$phone',email='$email' where id=$id";
- @mysql_query($sql);
- echo json_encode(array(
- 'id' => $id,
- 'firstname' => $firstname,
- 'lastname' => $lastname,
- 'phone' => $phone,
- 'email' => $email
- ));
刪除現有用戶(destroy_user.php):
- $id = intval($_REQUEST['id']);
- include 'conn.php';
- $sql = "delete from users where id=$id";
- @mysql_query($sql);
- echo json_encode(array('success'=>true));
edatagrid屬性
edatagrid的屬性從datagrid屬性中擴展,下面為edatagrid增加的屬性:
屬性名 |
類型 |
描述 |
默認值 |
destroyMsg |
object |
The confirm dialog message to display while destroying a row. |
destroyMsg:{ norecord:{ // when no record is selected title:'Warning', msg:'No record is selected.' }, confirm:{ // when select a row title:'Confirm', msg:'Are you sure you want to delete?' } }
|
autoSave |
boolean |
True to auto save the editing row when click out of datagrid. |
false |
url |
string |
A URL to retrieve data from server. |
null |
saveUrl |
string |
A URL to save data to server and return the added row. |
null |
updateUrl |
string |
A URL to update data to server and return the updated row. |
null |
destroyUrl |
string |
A URL to post 'id' parameter to server to destroy that row. |
null |
tree |
selector |
The tree selector to show the corresponding tree component. |
null |
treeUrl |
string |
A URL to retrieve the tree data. |
null |
treeDndUrl |
string |
A URL to process the drag and drop operation. |
null |
treeTextField |
string |
Defines the tree text field name. |
name |
treeParentField |
string |
Defines the tree parent node field name. |
parentId |
edatagrid事件
從datagrid擴展,下面為edatagrid增加的事件:
事件名 |
參數 |
描述 |
onAdd |
index,row |
Fires when a new row is added. |
onEdit |
index,row |
Fires when a row is editing. |
onBeforeSave |
index |
Fires before a row to be saved, return false to cancel this save action. |
onSave |
index,row |
Fires when a row is saved. |
onDestroy |
index,row |
Fires when a row is destroy. |
onError |
index,row |
Fires when the server errors occur. The server should return a row with 'isError' property set to true to indicate some errors occur. Code examples: //server side code echo json_encode(array( 'isError' => true, 'msg' => 'error message.' ));
//client side code $('#dg').edatagrid({ onError: function(index,row){ alert(row.msg); } });
|
edatagrid方法
從datagrid中擴展,下面是為edatagrid增加或重寫的方法:
方法名 |
參數 |
描述 |
options |
none |
Return the options object. |
enableEditing |
none |
Enable the datagrid editing. |
disableEditing |
none |
Disable the datagrid editing. |
editRow |
index |
Edit the specified row. |
addRow |
index |
Add a new row to the specified row index. If the index parameter is not specified, append the new row to the last position. Code examples: // append an empty row $('#dg').edatagrid('addRow');
// append an empty row as first row $('#dg').edatagrid('addRow',0);
// insert a row with default values $('#dg').edatagrid('addRow',{ index: 2, row:{ name:'name1', addr:'addr1' } });
|
saveRow |
none |
Save the editing row that will be posted to server. |
cancelRow |
none |
Cancel the editing row. |
destroyRow |
index |
Destroy the current selected row. If the index parameter is not specified, destroy all the selected rows. Code examples: // destroy all the selected rows $('#dg').edatagrid('destroyRow');
// destroy the first row $('#dg').edatagrid('destroyRow', 0);
// destroy the specified rows $('#dg').edatagrid('destroyRow', [3,4,5]); |
三、設定或定制各種功能
1、增加分頁
創建DataGrid數據表格
設置“url”屬性,用來裝入遠端服務器數據,服務器返回JSON格式數據。
- <table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
- url="datagrid2_getdata.php"
- title="Load Data" iconCls="icon-save"
- rownumbers="true" pagination="true">
- <thead>
- <tr>
- <th field="itemid" width="80">Item ID</th>
- <th field="productid" width="80">Product ID</th>
- <th field="listprice" width="80" align="right">List Price</th>
- <th field="unitcost" width="80" align="right">Unit Cost</th>
- <th field="attr1" width="150">Attribute</th>
- <th field="status" width="60" align="center">Stauts</th>
- </tr>
- </thead>
- </table>
定義datagrid列,將“pagination”屬性設為true,將會在datagrid底部生成一個分頁工具條。 pagination會發送兩個參數給服務器:
1、page: 頁碼,從1開始。
2、rows: 每頁顯示行數。
服務器端代碼
- $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
- $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
- // ...
- $rs = mysql_query("select count(*) from item");
- $row = mysql_fetch_row($rs);
- $result["total"] = $row[0];
- $rs = mysql_query("select * from item limit $offset,$rows");
- $items = array();
- while($row = mysql_fetch_object($rs)){
- array_push($items, $row);
- }
- $result["rows"] = $items;
- echo json_encode($result);
2、增加搜索
創建DataGrid
創建一個有分頁特性的datagrid,然后增加一個搜索工具條。
- <table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
- url="datagrid24_getdata.php" toolbar="#tb"
- title="Load Data" iconCls="icon-save"
- rownumbers="true" pagination="true">
- <thead>
- <tr>
- <th field="itemid" width="80">Item ID</th>
- <th field="productid" width="80">Product ID</th>
- <th field="listprice" width="80" align="right">List Price</th>
- <th field="unitcost" width="80" align="right">Unit Cost</th>
- <th field="attr1" width="150">Attribute</th>
- <th field="status" width="60" align="center">Stauts</th>
- </tr>
- </thead>
- </table>
工具條定義為:
- <div id="tb" style="padding:3px">
- <span>Item ID:</span>
- <input id="itemid" style="line-height:26px;border:1px solid #ccc">
- <span>Product ID:</span>
- <input id="productid" style="line-height:26px;border:1px solid #ccc">
- <a href="#" class="easyui-linkbutton" plain="true" onclick="doSearch()">Search</a>
- </div>
用戶輸入搜索值,然后點擊搜索按鈕,“doSearch”函數將會被調用:
- function doSearch() {
- $('#tt').datagrid('load', {
- itemid: $('#itemid').val(),
- productid: $('#productid').val()
- });
- }
上面的代碼調用“load”方法來裝載新的datagrid數據,同時需要傳遞“itemid”和“productid”參數到服務器。
服務器端代碼
- include 'conn.php';
- $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
- $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
- $itemid = isset($_POST['itemid']) ? mysql_real_escape_string($_POST['itemid']) : '';
- $productid = isset($_POST['productid']) ? mysql_real_escape_string($_POST['productid']) : '';
- $offset = ($page-1)*$rows;
- $result = array();
- $where = "itemid like '$itemid%' and productid like '$productid%'";
- $rs = mysql_query("select count(*) from item where " . $where);
- $row = mysql_fetch_row($rs);
- $result["total"] = $row[0];
- $rs = mysql_query("select * from item where " . $where . " limit $offset,$rows");
- $items = array();
- while($row = mysql_fetch_object($rs)){
- array_push($items, $row);
- }
- $result["rows"] = $items;
- echo json_encode($result);
3、獲取選擇行數據
本示例教你如何獲取選擇行數據。
Datagrid組件含有兩個方法用來接收選擇行數據:
- getSelected: 獲取所選擇行的第一行數據,如果沒有行被選擇返回null,否則返回數據記錄。
- getSelections: 獲取所有選擇行數據,返回數組數據,里面的數組元素就是數據記錄。
創建DataGrid
- <table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
- url="data/datagrid_data.json"
- title="Load Data" iconCls="icon-save">
- <thead>
- <tr>
- <th field="itemid" width="80">Item ID</th>
- <th field="productid" width="80">Product ID</th>
- <th field="listprice" width="80" align="right">List Price</th>
- <th field="unitcost" width="80" align="right">Unit Cost</th>
- <th field="attr1" width="150">Attribute</th>
- <th field="status" width="60" align="center">Stauts</th>
- </tr>
- </thead>
- </table>
實例用法
獲取單行數據:
- var row = $('#tt').datagrid('getSelected');
- if (row){
- alert('Item ID:'+row.itemid+"\nPrice:"+row.listprice);
- }
獲取所有行itemid:
- var ids = [];
- var rows = $('#tt').datagrid('getSelections');
- for(var i=0; i<rows.length; i++){
- ids.push(rows[i].itemid);
- }
- alert(ids.join('\n'));
4、增加工具條
本示例教你如何增加一個工具條到datagrid中。
創建DataGrid
- <table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
- url="data/datagrid_data.json"
- title="DataGrid with Toolbar" iconCls="icon-save"
- toolbar="#tb">
- <thead>
- <tr>
- <th field="itemid" width="80">Item ID</th>
- <th field="productid" width="80">Product ID</th>
- <th field="listprice" width="80" align="right">List Price</th>
- <th field="unitcost" width="80" align="right">Unit Cost</th>
- <th field="attr1" width="150">Attribute</th>
- <th field="status" width="60" align="center">Stauts</th>
- </tr>
- </thead>
- </table>
- <div id="tb">
- <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:alert('Add')">Add</a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="javascript:alert('Cut')">Cut</a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="javascript:alert('Save')">Save</a>
- </div>
5、復雜工具條
datagrid的工具條不僅僅只是包含按鈕,還可以是其它的組件。為方便布局,你可以通過現有的構成datagrid工具條的DIV來定義工具條。本教程教你如何創建一個復雜的工具條,作為datagrid的組件。
創建Toolbar
- <div id="tb" style="padding:5px;height:auto">
- <div style="margin-bottom:5px">
- <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true"></a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true"></a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true"></a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-cut" plain="true"></a>
- <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true"></a>
- </div>
- <div>
- Date From: <input class="easyui-datebox" style="width:80px">
- To: <input class="easyui-datebox" style="width:80px">
- Language:
- <input class="easyui-combobox" style="width:100px"
- url="data/combobox_data.json"
- valueField="id" textField="text">
- <a href="#" class="easyui-linkbutton" iconCls="icon-search">Search</a>
- </div>
- </div>
創建DataGrid
- <table class="easyui-datagrid" style="width:600px;height:250px"
- url="data/datagrid_data.json"
- title="DataGrid - Complex Toolbar" toolbar="#tb"
- singleSelect="true" fitColumns="true">
- <thead>
- <tr>
- <th field="itemid" width="60">Item ID</th>
- <th field="productid" width="80">Product ID</th>
- <th field="listprice" align="right" width="70">List Price</th>
- <th field="unitcost" align="right" width="70">Unit Cost</th>
- <th field="attr1" width="200">Address</th>
- <th field="status" width="50">Status</th>
- </tr>
- </thead>
- </table>
6、凍結列
本示例演示如何凍結數據列,當用戶水平滾動數據表格時,凍結的數據列不會滾動出視圖界面外。
通過定義frozenColumns屬性來凍結列,凍結列屬性的定義同列屬性。
- $('#tt').datagrid({
- title: 'Frozen Columns',
- iconCls: 'icon-save',
- width: 500,
- height: 250,
- url: 'data/datagrid_data.json',
- frozenColumns: [[{
- field: 'itemid',
- title: 'Item ID',
- width: 80
- },
- {
- field: 'productid',
- title: 'Product ID',
- width: 80
- },
- ]],
- columns: [[{
- field: 'listprice',
- title: 'List Price',
- width: 80,
- align: 'right'
- },
- {
- field: 'unitcost',
- title: 'Unit Cost',
- width: 80,
- align: 'right'
- },
- {
- field: 'attr1',
- title: 'Attribute',
- width: 100
- },
- {
- field: 'status',
- title: 'Status',
- width: 60
- }]]
- });
創建凍結列的datagrid可以不用編寫任何javascript代碼,如下面這樣:
- <table id="tt" title="Frozen Columns" class="easyui-datagrid" style="width:500px;height:250px"
- url="data/datagrid_data.json"
- singleSelect="true" iconCls="icon-save">
- <thead frozen="true">
- <tr>
- <th field="itemid" width="80">Item ID</th>
- <th field="productid" width="80">Product ID</th>
- </tr>
- </thead>
- <thead>
- <tr>
- <th field="listprice" width="80" align="right">List Price</th>
- <th field="unitcost" width="80" align="right">Unit Cost</th>
- <th field="attr1" width="150">Attribute</th>
- <th field="status" width="60" align="center">Stauts</th>
- </tr>
- </thead>
- </table>
7、格式化數據列
下面為EasyUI DataGrid里的格式化列示例,用一個定制的列格式化器(formatter)來將文本標注為紅色,如果價格低於20的話。
為格式化一個DataGrid列,我們需要設置格式化屬性,它是一個函數。格式化函數含有三個參數:
- value: 當前綁定的列字段值。
- row: 當前行記錄數據。
- index: 當前行索引。
創建DataGrid
- <table id="tt" title="Formatting Columns" class="easyui-datagrid" style="width:550px;height:250px"
- url="data/datagrid_data.json"
- singleSelect="true" iconCls="icon-save">
- <thead>
- <tr>
- <th field="itemid" width="80">Item ID</th>
- <th field="productid" width="80">Product ID</th>
- <th field="listprice" width="80" align="right" formatter="formatPrice">List Price</th>
- <th field="unitcost" width="80" align="right">Unit Cost</th>
- <th field="attr1" width="100">Attribute</th>
- <th field="status" width="60" align="center">Stauts</th>
- </tr>
- </thead>
- </table>
注意:“listprice”字段有一個“formatter”屬性,用來指明格式化函數。
編寫格式化函數
- function formatPrice(val,row){
- if (val < 20){
- return '<span style="color:red;">('+val+')</span>';
- } else {
- return val;
- }
- }
8、增加排序功能
本示例演示如何通過點擊列表頭來排序DataGrid數據。
DataGrid中的全部列都可以排序,可以定義哪一個列進行排序。默認列屬性不會進行排序,除非列的排序屬性sortable設置為true。
創建DataGrid
- <table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
- url="datagrid8_getdata.php"
- title="Load Data" iconCls="icon-save"
- rownumbers="true" pagination="true">
- <thead>
- <tr>
- <th field="itemid" width="80" sortable="true">Item ID</th>
- <th field="productid" width="80" sortable="true">Product ID</th>
- <th field="listprice" width="80" align="right" sortable="true">List Price</th>
- <th field="unitcost" width="80" align="right" sortable="true">Unit Cost</th>
- <th field="attr1" width="150">Attribute</th>
- <th field="status" width="60" align="center">Stauts</th>
- </tr>
- </thead>
- </table>
定義了可排序的列為:itemid、productid、listprice、unitcost等。“attr1”列和“status”列不能排序。
DataGrid的排序會發送兩個參數給服務器:
- sort: 排序列字段名。
- order: 排序方式,可以是“asc(升序)”或“desc(降序)”,默認為“asc”。
服務器端代碼
- $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
- $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
- $sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'itemid';
- $order = isset($_POST['order']) ? strval($_POST['order']) : 'asc';
- $offset = ($page-1)*$rows;
- $result = array();
- include 'conn.php';
- $rs = mysql_query("select count(*) from item");
- $row = mysql_fetch_row($rs);
- $result["total"] = $row[0];
- $rs = mysql_query("select * from item order by $sort $order limit $offset,$rows");
- $items = array();
- while($row = mysql_fetch_object($rs)){
- array_push($items, $row);
- }
- $result["rows"] = $items;
- echo json_encode($result);
9、增加選擇框
本教程教你如何放置一個checkbox 列到 DataGrid中。利用選擇框用戶可以即刻選擇/取消所有表格數據行。
為增加一個checkbox列,我們只需簡單將checkbox屬性設置為true即可。代碼如下所示:
- <table id="tt" title="Checkbox Select" class="easyui-datagrid" style="width:550px;height:250px"
- url="data/datagrid_data.json"
- idField="itemid" pagination="true"
- iconCls="icon-save">
- <thead>
- <tr>
- <th field="ck" checkbox="true"></th>
- <th field="itemid" width="80">Item ID</th>
- <th field="productid" width="80">Product ID</th>
- <th field="listprice" width="80" align="right">List Price</th>
- <th field="unitcost" width="80" align="right">Unit Cost</th>
- <th field="attr1" width="100">Attribute</th>
- <th field="status" width="60" align="center">Status</th>
- </tr>
- </thead>
- </table>
上面的代碼增加了一個含有checkbox屬性的列,從而生成了一個選擇框列。如果idField屬性被設置,DataGrid的已選行在不同的頁面里都可以維持。
10、增強行內編輯
Datagrid最近增加了一個可編輯功能,它使用戶可增加新行到datagrid中,用戶也可對單行或多行數據進行更新。
本教程教你如何創建一個帶有行編輯功能的datagrid。
創建DataGrid
- $(function() {
- $('#tt').datagrid({
- title: 'Editable DataGrid',
- iconCls: 'icon-edit',
- width: 660,
- height: 250,
- singleSelect: true,
- idField: 'itemid',
- url: 'datagrid_data.json',
- columns: [[{
- field: 'itemid',
- title: 'Item ID',
- width: 60
- },
- {
- field: 'productid',
- title: 'Product',
- width: 100,
- formatter: function(value) {
- for (var i = 0; i < products.length; i++) {
- if (products[i].productid == value) return products[i].name;
- }
- return value;
- },
- editor: {
- type: 'combobox',
- options: {
- valueField: 'productid',
- textField: 'name',
- data: products,
- required: true
- }
- }
- },
- {
- field: 'listprice',
- title: 'List Price',
- width: 80,
- align: 'right',
- editor: {
- type: 'numberbox',
- options: {
- precision: 1
- }
- }
- },
- {
- field: 'unitcost',
- title: 'Unit Cost',
- width: 80,
- align: 'right',
- editor: 'numberbox'
- },
- {
- field: 'attr1',
- title: 'Attribute',
- width: 150,
- editor: 'text'
- },
- {
- field: 'status',
- title: 'Status',
- width: 50,
- align: 'center',
- editor: {
- type: 'checkbox',
- options: {
- on: 'P',
- off: ''
- }
- }
- },
- {
- field: 'action',
- title: 'Action',
- width: 70,
- align: 'center',
- formatter: function(value, row, index) {
- if (row.editing) {
- var s = '<a href="#" onclick="saverow(this)">Save</a> ';
- var c = '<a href="#" onclick="cancelrow(this)">Cancel</a>';
- return s + c;
- } else {
- var e = '<a href="#" onclick="editrow(this)">Edit</a> ';
- var d = '<a href="#" onclick="deleterow(this)">Delete</a>';
- return e + d;
- }
- }
- }]],
- onBeforeEdit: function(index, row) {
- row.editing = true;
- updateActions(index);
- },
- onAfterEdit: function(index, row) {
- row.editing = false;
- updateActions(index);
- },
- onCancelEdit: function(index, row) {
- row.editing = false;
- updateActions(index);
- }
- });
- });
- function updateActions(index) {
- $('#tt').datagrid('updateRow', {
- index: index,
- row: {}
- });
- }
為了讓datagrid可編輯數據,要增加一個editor屬性到列屬性里,編輯器會告訴datagrid如何編輯字段和如何保存字段值,這里定義了三個editor:text、combobox和checkbox。
- function getRowIndex(target) {
- var tr = $(target).closest('tr.datagrid-row');
- return parseInt(tr.attr('datagrid-row-index'));
- }
- function editrow(target) {
- $('#tt').datagrid('beginEdit', getRowIndex(target));
- }
- function deleterow(target) {
- $.messager.confirm('Confirm', 'Are you sure?',
- function(r) {
- if (r) {
- $('#tt').datagrid('deleteRow', getRowIndex(target));
- }
- });
- }
- function saverow(target) {
- $('#tt').datagrid('endEdit', getRowIndex(target));
- }
- function cancelrow(target) {
- $('#tt').datagrid('cancelEdit', getRowIndex(target));
- }
11、擴展編輯器
一些通用編輯器被加入到datagrid中,用來允許用戶編輯數據。所有編輯器在 $.fn.datagrid.defaults.editors對象中進行定義,被擴展來支持新編輯器。本教程教你如何增加一個新的numberspinner編輯器到datagrid中。
擴展numberspinner編輯器
- $.extend($.fn.datagrid.defaults.editors, {
- numberspinner: {
- init: function(container, options) {
- var input = $('<input type="text">').appendTo(container);
- return input.numberspinner(options);
- },
- destroy: function(target) {
- $(target).numberspinner('destroy');
- },
- getValue: function(target) {
- return $(target).numberspinner('getValue');
- },
- setValue: function(target, value) {
- $(target).numberspinner('setValue', value);
- },
- resize: function(target, width) {
- $(target).numberspinner('resize', width);
- }
- }
- });
在html標識理創建DataGrid
- <table id="tt" style="width:600px;height:250px"
- url="data/datagrid_data.json" title="Editable DataGrid" iconCls="icon-edit"
- singleSelect="true" idField="itemid" fitColumns="true">
- <thead>
- <tr>
- <th field="itemid" width="60">Item ID</th>
- <th field="listprice" width="80" align="right" editor="{type:'numberbox',options:{precision:1}}">List Price</th>
- <th field="unitcost" width="80" align="right" editor="numberspinner">Unit Cost</th>
- <th field="attr1" width="180" editor="text">Attribute</th>
- <th field="status" width="60" align="center" editor="{type:'checkbox',options:{on:'P',off:''}}">Status</th>
- <th field="action" width="80" align="center" formatter="formatAction">Action</th>
- </tr>
- </thead>
- </table>
指定numberspinner編輯器到“unit cost”字段,當啟動編輯行,用戶就可以利用numberspinner編輯器組件來編輯數據。