在上一篇中我们使用对话框组件创建了CRUD应用创建和编辑用户信息。本篇我们来创建一个CRUD数据网格DataGrid
步骤1,在HTML标签中定义数据网格(DataGrid)
1 <table id="dg" title="My Users" style="width:550px;height:250px" 2 toolbar="#toolbar" idField="id" 3 rownumbers="true" fitColumns="true" singleSelect="true"> 4 <thead> 5 <tr> 6 <th field="firstname" width="50" editor="{type:'validatebox',options:{required:true}}">First Name</th> 7 <th field="lastname" width="50" editor="{type:'validatebox',options:{required:true}}">Last Name</th> 8 <th field="phone" width="50" editor="text">Phone</th> 9 <th field="email" width="50" editor="{type:'validatebox',options:{validType:'email'}}">Email</th> 10 </tr> 11 </thead> 12 </table> 13 <div id="toolbar"> 14 <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:$('#dg').edatagrid('addRow')">New</a> 15 <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="javascript:$('#dg').edatagrid('destroyRow')">Destroy</a> 16 <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="javascript:$('#dg').edatagrid('saveRow')">Save</a> 17 <a href="#" class="easyui-linkbutton" iconCls="icon-undo" plain="true" onclick="javascript:$('#dg').edatagrid('cancelRow')">Cancel</a> 18 </div>
步骤2、使用可编辑的数据网格(DataGrid)
1 $('#dg').edatagrid({ 2 url: 'get_users.php', 3 saveUrl: 'save_user.php', 4 updateUrl: 'update_user.php', 5 destroyUrl: 'destroy_user.php' 6 });
我们应该提供 url saveUrl updateUrl destoryUrl属性来编辑数据网格DataGrid
url:从服务器检索用户数据
saveUrl:保存一个新的用户数据
updateUrl:更新一个已存在的用户数据
destroyUrl:删除一个已存在的用户数据
步骤3、写服务器处理代码
保存一个新的用户 save_user.php
1 $firstname = $_REQUEST['firstname']; 2 $lastname = $_REQUEST['lastname']; 3 $phone = $_REQUEST['phone']; 4 $email = $_REQUEST['email']; 5 6 include 'conn.php'; 7 8 $sql = "insert into users(firstname,lastname,phone,email) values('$firstname','$lastname','$phone','$email')"; 9 @mysql_query($sql); 10 echo json_encode(array( 11 'id' => mysql_insert_id(), 12 'firstname' => $firstname, 13 'lastname' => $lastname, 14 'phone' => $phone, 15 'email' => $email 16 ));
更新一个已存在用户update_user.php:
1 $id = intval($_REQUEST['id']); 2 $firstname = $_REQUEST['firstname']; 3 $lastname = $_REQUEST['lastname']; 4 $phone = $_REQUEST['phone']; 5 $email = $_REQUEST['email']; 6 7 include 'conn.php'; 8 9 $sql="update users set firstname='$firstname',lastname='$lastname',phone='$phone',email='$email' where id=$id"; 10 @mysql_query($sql); 11 echo json_encode(array( 12 'id' => $id, 13 'firstname' => $firstname, 14 'lastname' => $lastname, 15 'phone' => $phone, 16 'email' => $email 17 ));
删除一个已存在用户destroy_user.php
1 $id = intval($_REQUEST['id']); 2 3 include 'conn.php'; 4 5 $sql = "delete from users where id=$id"; 6 @mysql_query($sql); 7 echo json_encode(array('success'=>true));