EasyUI DataGrid結合ThinkPHP實現增刪改查操作———初學者


EasyUI是基於jQuery的用戶界面插件集合;DataGrid是數據表格;

ThinkPHP是快速、簡單的基於MVC和面向對象的輕量級PHP開發框架。

使用的集成開發環境是 WAMPSever,(wampserver是一個集成了Apache、PHP和MySQL的開發套件,而且支持不同PHP版本、MySQL版本和Apache版本的切換)

效果如下

 

主要代碼如下

 1、定義一個表格

     

<table id="dg" class="easyui-datagrid" title="DataGrid Complex Toolbar" style="width:700px;height:250px"
            data-options="rownumbers:true,singleSelect:true,url:'{:U(read)}',method:'get',toolbar:'#tb'">
        <thead>
            <tr>
                <th data-options="field:'ID',width:80,align:'center'">ID</th>
                <th data-options="field:'Product',width:100">Product</th>
                <th data-options="field:'Content',width:500,align:'center'">Content</th>
            </tr>
        </thead>
</table>

 

  class="easyui-datagrid"是easyui里面自定義的格式,data-options用來初始化屬性,這里面的屬性包括rownumbers顯示行數,singleSelect表示行的選中狀態;

url:'{U(read)}'首先,ThinkPHP的U方法(參考:http://www.thinkphp.cn/info/132.html)用來完成對URL地址的組裝,在模板中的調用采用 {:U('地址', '參數'…)} 的方式,其次,EasyUI采用的數據格式是json,控制器里面的read方法輸出一個json格式的數據。toolbar:'#tb'這個是表格的工具欄,就是增加、刪除和修改。

定義表格的工具欄如下:

<div id="tb" style="padding:2px 5px;">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onClick="addPro()"></a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editPro()"></a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removePro()"></a>
 </div>

注意:這里面的id要和 toolbar:'#tb' 相對應;

2、點擊增加和修改的時候要彈出一個對話框,代碼如下:

<!--the page of dialog-->
    <div id="dl" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px" closed="true" footer="ft" buttons="#dlg-buttons">
       <div class="ftitle">Information</div>
       <form id="am" method="post" novalidate >
             Product:<input type="text" name="Product" class="easyui-validatebox" required="true"/></br>
             Content:<Textarea name="Content" rows="5" cols="45"></Textarea></br>
       </form>
    </div>  

class='easyui-dialog'定義了一個對話框,因為要和后台交互,在這個對話框里面裝了一個form,里面的input元素有些需要進行驗證,required="true"表示必須填寫元素

class="easyui-validatebox"定義了驗證失敗后的提示,buttons="#dlg-buttons"表示這個對話框下面的兩個確認,取消按鈕。novalidate表示不驗證。

 對話框中的按鈕:

<div id="dlg-buttons">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="savePro()">Save</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" 
          onclick="javascript:$('#dl').dialog('close')">Cancel</a>
</
div>

 3、頁面js函數

  <script type="text/javascript"> 
        var url;
        function addPro(){
              $('#dl').dialog('open').dialog('setTitle','New Information');
              $('#am').form('clear');
              url = '__URL__/insert';
       }
        function editPro(){
            var row = $("#dg").datagrid("getSelected");//取得選中行
            if(row){ 
               $("#dl").dialog("open").dialog("setTitle","Change Information");
               $("#am").form("load",row);
               url = '__URL__/update?ID='+row.ID;//為update方法准備訪問url,注意是全局變量
            }
        } 
        
       function savePro(){
            $('#am').form('submit',{
                url: url,
                onSubmit: function(){
                    return $(this).form('validate');
                },
                success: function(result){
                    var result = eval('('+result+')');
                    if (result.success){
                        $('#dl').dialog('close');        // close the dialog
                        $('#dg').datagrid('reload');    // reload the user data
                    } else {
                        $.messager.show({
                            title: 'Error',
                            msg: result.msg
                        });
                    }
                }
            });
        }
        
      function removePro()
       {
          var row = $('#dg').datagrid('getSelected');
            if (row){
                $.messager.confirm('Confirm','Are you sure you want to remove this row?',function(r){
                    if (r){
                        $.post('__URL__/delete',{ID:row.ID},function(result){
                            if (result.success){
                                $('#dg').datagrid('reload');    // reload the user data
                            } else {
                                $.messager.show({    // show error message
                                    title: 'Error',
                                    msg: result.msg
                                });
                            }
                        },'json');
                    }
                });
            }
     }
    </script>

 JS還不是很會,所以參考了網上的代碼。 $.messager.show是EasyUI提供的消息提示框(參考:http://www.jeasyui.net/demo/371.html),可以在屏幕右下角顯示一個消息窗口。$.messager.confirm是交互式消息,彈出一個消息確認框。var row = $("#dg").datagrid("getSelected");是取得選中行,而row.ID可以取得選中行的數據,其中ID是由field:'ID'決定。

4、控制器里面的代碼(IndexAction.class.php) 

<?php
// 本類由系統自動生成,僅供測試用途
class IndexAction extends Action {
    public function index(){
      $this->display();
    } 
     publicfunction read(){
$Test = M('test');
        /*$Total = $Test->count();
        $Json = '{"total":'.$Total.',"rows":'.json_encode($Test->select()).'}';*/
        $Json = json_encode($Test->select());
        echo $Json;
 }

public
function insert(){ $data = $this->_post(); $Test = M('Test'); $result = $Test->add($data); if($result) { echo json_encode(array('success'=>true)); }else { echo json_encode(array('msg'=>'Some error occured')); } } public function update($ID=0){ $Test = M('test'); $ID = $_GET['ID']; if($Test->create()) { $Test->ID = $ID; $result = $Test->save(); if($result) { echo json_encode(array('success'=>true)); }else { echo json_encode(array('msg'=>'Some error occured')); } }else{ $this->error($Test->getError()); } } public function delete($ID=0){ $result = false; $Test = M('test'); $result = $Test->where('ID='.$ID)->delete(); if($result==false){ echo json_encode(array('msg'=>'刪除出錯!')); }else{ echo json_encode(array('success'=>true)); } } } ?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM