EasyUI DataGrid 是一个用Jquery写的DataGrid,由此可知,是一个前端Web UI 技术,一般大家在产生 DataGrid 比较常见的应该就是使用后台 PHP 等后台语言,来直接产生 HTML 语法,来显示 DataGrid,当要对该 DataGrid 操作时,在传递参数到后端,重新产生整各网页。
而 EasyUI DataGrid 支持两种做法,一个是上述,后台 server 把显示的 HTML 产生好,在给前端显示。另一种是,利用 AJAX 的方式来产生,就只是单纯为JSON 格式资料给前端,前端接收到资料后,在自己分析资料利用 JQuery 来刷新 DataGrid 该部分的画面。
这边介绍的是第二种做法,利用 AJAX 技术来做,这样的好处,是可以把 资料层-> 控制层-> 展示层 三层独立来运作,达到我在之前 多层次架构设计前言 所讲的精神,不会像老方法,把 HTML 的产生都放在 PHP 中来产生,造成 PHP 开发人员本身,也要对 HTML 等前端技术也要了解很深才能进行开发的问题。
在来如此作法,为带来另一种好处,就是你前端的 UI 是可以更换,而后台程式却不用来大幅修改。目前支持 JSON 资料格式的 JavaScript DataGrid 有很多种,大家也可以多去参考其他的公司所提供的 DataGrid ,从中选择一个最适合的来使用。
介绍到此,接下来直接看程式代码,会更加了解我上述的意思:
首先,需要先设计 HTML UI 介面,定义要显示哪些栏位,栏位的显示名称等,关于这部分的栏位定义,EasyUI DataGrid 也是有提供,使用 JavaScript 来动态定义,而我习惯用 HTML 直接定义,这样 也不复杂,后面在分工上,也比较容易来直接交给 Web 美工人员来直接操作。这部分重点在 URL 的设定。
DataGrid2.php
代码如下:
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<meta name=”keywords” content=”jquery,ui,easy,easyui,web”>
<meta name=”description” content=”easyui help you build your web page easily!”>
<title>一條小龍 easyUI datagrid</title>
<link rel=”stylesheet” type=”text/css” href=”./JS/EasyUI/themes/default/easyui.css”>
<link rel=”stylesheet” type=”text/css” href=”./JS/EasyUI/themes/icon.css”>
<script type=”text/javascript” src=”./JS/jquery.js”></script>
<script type=”text/javascript” src=”./JS/EasyUI/jquery.easyui.min.js”></script>
</head>
<body>
<h2>一條小龍 easyUI datagrid url test</h2>
<table id=”tt” style=”width:750px;height:300px”
url=”datagrid2_getdata.php” title=”Load Data” pagination=”true”>
<thead>
<tr>
<th field=”UNum” width=”80″>UNum</th>
<th field=”STUID” width=”120″>User ID</th>
<th field=”Password” width=”80″ align=”right”>Password</th>
<th field=”Birthday” width=”80″ align=”right”>Birthday</th>
<th field=”Nickname” width=”200″>Nickname</th>
<th field=”DBSTS” width=”60″ align=”center”>DBSTS</th>
</tr>
</thead>
</table>
</body>
</html>
在来定义资料取得的后台介面
datagrid2_getdata.php
代码如下:
<?php
$page = isset($_POST[‘page’]) ? intval($_POST[‘page’]) : 1;
$rows = isset($_POST[‘rows’]) ? intval($_POST[‘rows’]) : 10;
$offset = ($page-1)*$rows;
$result = array();
$tablename = “STUser”;
// …
require_once(“.dbDB_config.php”);
require_once(“.dbDB_class.php”);
$db = new DB();
$db->connect_db($_DB[‘host’], $_DB[‘username’], $_DB[‘password’], $_DB[‘dbname’]);
$db->query(“select count(*) As Total from $tablename”);
$row = $db->fetch_assoc();
$result[“total”] = $row[“Total”];
$db->query(“select * from $tablename limit $offset,$rows”);
$items = array();
while($row = $db->fetch_assoc()){
array_push($items, $row);
}
$result[“rows”] = $items;
echo json_encode($result);
?>
由上述,可以看出,这是一个很单纯的资料取得的动作。
一开始 DataGrid 会传进来两个参数,
$_POST[‘page’]) 目前是在第几页
$_POST[‘rows’]) 每页要显示几笔资料
然后,要使用一个阵列 $result ,存放两个资讯,
$result[“total”] 有几笔资料
$result[“rows”] 存放实际的资料阵列集
最后要将 $result 阵列,产生将 JSON 资料格式来输出,DataGrid 接收到以后就会来处理、刷新画面了。
后面,在更进一步,可以将 datagrid2_getdata.php 在抽象化一层,也就是将属于 EasyUI DataGrid 特有的资料格式处理的部分与资料库存取的的部分分离,各自独立出来成为 两个 class 来处理。
一个好的架构 以及 class 设计,其实都是靠经验的累积而生成的,不断演进改良,原有的框架,其中最重要的精神就是,每个 Class 的分工要清楚而且精确,这是为了应付上述,不断演进 这各问题来做的对应措施,这样在未来才更容易去做修改调整。
否则更容易变成,你想改却不知从何下手,因为一改就有几十行,甚至上百行程序等着你,要一起修改,从而延伸出,稳定性问题,也就是大家反对去修改原有系统,就是因为太多要改了,少改一支也不行,问题几十支一起改,就算都改完,谁来测试有没有改好,难道叫你的 user 来帮你测,想想,就还是算了,不要再改了,反正现在系统也都还好好的可以用。
继上篇文章 PHP – EasyUI DataGrid 资料取的方式,本篇继续讲述,如何操作 DataGrid,把资料存入资料库,并实现 MVC 架构,将资料层分离、独立运作。
本篇文章主要是改良,原 EasyUI DataGrid 的范例 Build CRUD Application with jQuery EasyUI。
在官方范例中已经示范如何操作资料,但其中有个问题就是,你要操作资料的每个动作都需要一支对应的程式才能动作,像是新增、删除、修改以及取得资料,总共至少要有四支对应程式才能运作。
读者可以想想,这还只是一支单档 使用者的基本资料维护而已,一般系统光基本资料都有十几支甚至几十支程式在运作,所以这样的方式,势必要改良才能运作在实务上。
在来按造 多层次架构设计前言的精神,大家可以发现这四支程式其实对每一个基本资料的操作来说,都是大同小异的,所以是可以把他标准化,用成一个固定框架,供后面类似程式来使用。
这部分,会分几篇文章来逐渐完成这各过程,藉由这逐渐演进的过程,来了解框架是如何成形的。
首先本篇,先来介绍,如何把分散的四支程式集中成为一支程式来呼叫,在读者往下阅读之前,可先在了解 PHP – EasyUI DataGrid 资料取的方式 以及官方范例 Build CRUD Application with jQuery EasyUI 的运作方式,至少要能把范例 Run 起来,run 这个动作是很重要的,不要光看而已,亲身去测试才能了解其中的问题点。
要能实现将四支程式改成一支程式来运作,其实关键很简单,就是去改每个操作动作时呼叫的 url,改成都呼叫 DAL 端的程式 dal_user.php,接下来在呼叫前,都要传递一个 type 参数告诉 dal 你要进行何种动作。
目前 type 定义了下面四个动作
add 新增
mod 修改
del 删除
data 取得资料
了解 想要 dal 作哪些动作后,就可以开始来撰写 dal 程式了,当然现在这各 dal 还是一个非标准化的程式,但是他已经做到 MVC 的精神,把资料存取层跟表现层 分离开了,后面的文章, 会再来介绍,如何把本篇介绍的程式来标准化 dal 以及 UI 表现层。
dal_user.php
<?php
$result = false;
if (!empty($_REQUEST[‘type’]) )
{
require_once(“…dbDB_config.php”);
require_once(“…dbDB_class.php”);
$db = new DB();
$db->connect_db($_DB[‘host’], $_DB[‘username’], $_DB[‘password’], $_DB[‘dbname’]);
$tablename = “STUser”;
$type = $_REQUEST[‘type’];
if($type == “del”)
{
$id = $_REQUEST[‘id’];
$sql = “delete from STUser where UNum=$id”;
$result = $db->query($sql);
}else if($type == “data”){
$page = isset($_POST[‘page’]) ? intval($_POST[‘page’]) : 1;
$rows = isset($_POST[‘rows’]) ? intval($_POST[‘rows’]) : 10;
$offset = ($page-1)*$rows;
$result = array();
$db->query(“select count(*) As Total from $tablename”);
$row = $db->fetch_assoc();
$result[“total”] = $row[“Total”];
$db->query(“select * from $tablename limit $offset,$rows”);
$items = array();
while($row = $db->fetch_assoc()){
array_push($items, $row);
}
$result[“rows”] = $items;
echo json_encode($result);
}else{
$STUID = $_REQUEST[‘STUID’];
$Password = $_REQUEST[‘Password’];
$Nickname = $_REQUEST[‘Nickname’];
$Birthday = $_REQUEST[‘Birthday’];
if (!empty($_REQUEST[‘id’]) ) {
$id = $_REQUEST[‘id’];
$sql = “update $tablename set STUID=’$STUID’,Password=’$Password’,Nickname=’$Nickname’ where UNum=$id”;
}else{ // is add
$sql = “insert into $tablename (STUID, Password, Nickname, DBSTS) values(‘$STUID’,’$Password’,’$Nickname’, ‘A’)”;
}
$result = $db->query($sql);
}
}
if($type != “data”)
{
if ($result == “true”){
echo json_encode(array(‘success’=>true));
} else {
echo json_encode(array(‘msg’=>’had errors occured. ‘ . $result));
}
}
?>
dal 资料存取层 定义完了以后,就可以来实现 UI 介面来呼叫 dal,因为是使用 AJAX 的方式 来存取资料,所以 MVC 中的控制层有一部分是放在介面层中,这部分,后面可以在用 JavaScript 将这部分的控制层标准化,在藉由 php 后端来传递参数呼叫,如此一来,则还是将所有控制大权集中在一支程式中,这些后面文章会再来介绍,这边先暂时打住。
datagrid.php
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>easyUI datagrid</title>
<link rel=”stylesheet” type=”text/css” href=”./../JS/EasyUI/themes/default/easyui.css”>
<link rel=”stylesheet” type=”text/css” href=”./../JS/EasyUI/themes/icon.css”>
<script type=”text/javascript” src=”./../JS/jquery.js”></script>
<script type=”text/javascript” src=”./../JS/EasyUI/jquery.easyui.min.js”></script>
<script type=”text/javascript” src=”./../JS/EasyUI/easyui-lang-zh_CN.js”></script>
<style type=”text/css”>
#fm{
margin:0;
padding:10px 30px;
}
.ftitle{
font-size:14px;
font-weight:bold;
color:#666;
padding:5px 0;
margin-bottom:10px;
border-bottom:1px solid #ccc;
}
.fitem{
margin-bottom:5px;
}
.fitem label{
display:inline-block;
width:80px;
}
</style>
<script type=”text/javascript”>
var url;
function newUser(){
$(‘#dlg’).dialog(‘open’).dialog(‘setTitle’,’New User’);
$(‘#fm’).form(‘clear’);
url = ‘dal_user.php?type=add’;
}
function editUser(){
var row = $(‘#myDG’).datagrid(‘getSelected’);
if (row){
if(typeof(row.UNum) !== ‘undefined’)
{
$(‘#dlg’).dialog(‘open’).dialog(‘setTitle’,’Edit User’);
$(‘#fm’).form(‘load’,row);
url = ‘dal_user.php?type=mod&id=’+row.UNum;
}else{
alert(“undefined”);
}
}
}
function saveUser(){
$(‘#fm’).form(‘submit’,{
url: url,
onSubmit: function(){
//alert(‘sub :’+ url);
return $(this).form(‘validate’);
},
success: function(result){
var result = eval(‘(‘+result+’)’);
//alert(result.success);
if (result.success){
$(‘#dlg’).dialog(‘close’); // close the dialog
$(‘#myDG’).datagrid(‘reload’); // reload the user data
} else {
$.messager.show({
title: ‘Error’,
msg: result.msg
});
}
}
});
}
function removeUser(){
var row = $(‘#myDG’).datagrid(‘getSelected’);
if (row){
$.messager.confirm(‘Confirm’,’Are you sure you want to remove this user?’,function(r){
if (r){
//alert(row.UNum);
$.post(‘dal_user.php’, {type:’del’, id:row.UNum}, function(result){
if (result.success){
$(‘#myDG’).datagrid(‘reload’); // reload the user data
} else {
$.messager.show({ // show error message
title: ‘Error’,
msg: result.msg
});
}
},’json’);
}
});
}
}
</script>
</head>
<body>
<h2>easyUI datagrid url 存取測試</h2>
<table id=”myDG” style=”width:700px;height:450px”
url=”dal_user.php?type=data” toolbar=”#toolbar”
title=”Load Data” iconCls=”icon-save” pagination=”true”
toolbar=”#toolbar” rownumbers=”true” fitColumns=”true” singleSelect=”true”>
<thead>
<tr>
<th field=”STUID” width=”120″>User ID</th>
<th field=”Password” width=”80″ align=”right”>Password</th>
<th field=”Birthday” width=”80″ align=”right”>Birthday</th>
<th field=”Nickname” width=”200″>Nickname</th>
<th field=”DBSTS” width=”60″ align=”center”>DBSTS</th>
</tr>
</thead>
</table>
<div id=”toolbar”>
<a href=”#” iconCls=”icon-add” plain=”true” onclick=”newUser()”>New User</a>
<a href=”#” iconCls=”icon-edit” plain=”true” onclick=”editUser()”>Edit User</a>
<a href=”#” iconCls=”icon-remove” plain=”true” onclick=”removeUser()”>Remove User</a>
</div>
<div id=”dlg” style=”width:400px;height:350px;padding:10px 20px”
closed=”true” buttons=”#dlg-buttons”>
<div>User Information</div>
<form id=”fm” method=”post” novalidate>
<div>
<label>User ID:</label>
<input name=”STUID” required=”true”>
</div>
<div>
<label>Password:</label>
<input name=”Password” required=”true”>
</div>
<div>
<label>Nickname:</label>
<input name=”Nickname”>
</div>
<div>
<label>Birthday:</label>
<input name=”Birthday” validType=”email”>
</div>
</form>
</div>
<div id=”dlg-buttons”>
<a href=”#” iconCls=”icon-ok” onclick=”saveUser()”>Save</a>
<a href=”#” iconCls=”icon-cancel” onclick=”javascript:$(‘#dlg’).dialog(‘close’)”>Cancel</a>
</div>
</body>
</html>

结果画面,如下所示: