在创建CRUD应用一节内容中,你已经了解如何通过对话框组件创建CRUD应用来对用户的信息进行创建与编辑。
在本节内容中,我们将告诉您如何创建一个CRUD数据网格(DataGrid)。我们将使用可编辑的数据网格(DataGrid)插件来完成这些CRUD操作动作。
<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>
$('#dg').edatagrid({
url: 'get_users.php',
saveUrl: 'save_user.php',
updateUrl: 'update_user.php',
destroyUrl: 'destroy_user.php'
});
我们通过'url'、'saveUrl'、'updateUrl'和'destroyUrl'属性来编辑数据网格(DataGrid),这些属性的作用如下:
保存一个新的用户(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));