Jquery EasyUI后台实例

首先是一个布局

左边是个Accordion

右边主要区域是Tabs

还有个例子很典型的左右结构:左边树(Tree),右边表格(datagrid)

ok,代码如下:

1.主页代码

<head>
    <title></title>
    <link href="js/themes/default/easyui.css" rel="stylesheet" type="text/css" />
    <link href="js/themes/icon.css" rel="stylesheet" type="text/css" />
    <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="js/jquery.easyui.min.js" type="text/javascript"></script>
    <script src="Default.js" type="text/javascript"></script>
    <style type="text/css">
        .easyui-accordion ul
        {
            list-style-type: none;
            margin: 0px;
            padding: 10px;
        }
        .easyui-accordion ul li
        {
            padding: 0px;
        }
        .easyui-accordion ul li a
        {
            line-height: 24px;
        }
        .easyui-accordion ul li div
        {
            margin: 2px 0px;
            padding-left: 10px;
            padding-top: 2px;
        }
        .easyui-accordion ul li div.hover
        {
            border: 1px dashed #99BBE8;
            background: #E0ECFF;
            cursor: pointer;
        }
        .easyui-accordion ul li div.hover a
        {
            color: #416AA3;
        }
        .easyui-accordion ul li div.selected
        {
            border: 1px solid #99BBE8;
            background: #E0ECFF;
            cursor: default;
        }
        .easyui-accordion ul li div.selected a
        {
            color: #416AA3;
            font-weight: bold;
        }
    </style>
</head>
<body class="easyui-layout" style="overflow-y: hidden" scroll="no">
    <noscript>
        <div style="position: absolute; z-index: 100000; height: 2046px; top: 0px; left: 0px;
            width: 100%; background: white; text-align: center;">
            <img src="images/noscript.gif" alt='抱歉,请开启脚本支持!' />
        </div>
    </noscript>
    <div region="north" split="true" style="overflow: hidden; height: 30px; background: #D2E0F2 repeat-x center 50%;
        line-height: 20px; color: #fff;">
        欢迎使用
    </div>
    <div region="south" style="height: 20px; background: #D2E0F2;">
        <div style="text-align: center; font-weight: bold">
            EntWebSite ver 1.0</div>
    </div>
    <div region="west" split="true" title="导航菜单" style="width: 180px;overflow:hidden;" icon="icon-redo">
        <div id="menu" class="easyui-accordion" fit="true" border="false">
            <div title="系统管理" style="overflow:auto; padding: 10px;" icon="icon-edit">
                <div title="网站设置">
                    <ul>
                        <li>
                            <div>
                                <a target="mainFrame" href="Product/Default.htm">网站设置</a></div>
                        </li>
                    </ul>
                </div>
            </div>
            <div title="产品管理" style="padding: 10px;" icon="icon-edit">
                <div title="产品管理">
                    <ul>
                        <li>
                            <div>
                                <a target="mainFrame" href="Product/Default.htm">产品管理</a></div>
                        </li>
                    </ul>
                </div>
            </div>
            <div title="关于" icon="icon-help">
                <h4>
                    EntWebSite Ver 1.0</h4>
            </div>
        </div>
    </div>
    <div region="center" id="mainPanle" style="background: #eee;overflow:hidden;">
        <div id="tabs" class="easyui-tabs" fit="true" border="false">
            <div title="主页" style="padding: 20px;" id="home">
                <h1>
                    Welcome...</h1>
            </div>
        </div>
    </div>
</body>

其中Default.js代码如下:

代码Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->$(function () {
    InitLeftMenu();
    $('body').layout();
})

function InitLeftMenu() {
    $('.easyui-accordion li a').click(function () {
        var tabTitle = $(this).text();
        var url = $(this).attr("href");
        addTab(tabTitle, url);
        $('.easyui-accordion li div').removeClass("selected");
        $(this).parent().addClass("selected");
    }).hover(function () {
        $(this).parent().addClass("hover");
    }, function () {
        $(this).parent().removeClass("hover");
    });
}

function addTab(subtitle, url) {
    if (!$('#tabs').tabs('exists', subtitle)) {
        $('#tabs').tabs('add', {
            title: subtitle,
            content: createFrame(url),
            closable: true,
            width: $('#mainPanle').width() - 10,
            height: $('#mainPanle').height() - 26
        });
    } else {
        $('#tabs').tabs('select', subtitle);
    }
}

function createFrame(url) {
    var s = '<iframe name="mainFrame" scrolling="no" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>';
    return s;
}

2.Tab页中管理页面代码

<head>
    <title></title>
    <link href="../js/themes/default/easyui.css" rel="stylesheet" type="text/css" />
    <link href="../js/themes/icon.css" rel="stylesheet" type="text/css" />
    <script src="../js/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="../js/jquery.easyui.min.js" type="text/javascript"></script>
    <script src="../js/locale/easyui-lang-zh_CN.js" type="text/javascript"></script>
    <script src="Default.js" type="text/javascript"></script>
</head>
<body class="easyui-layout" style="overflow-y: hidden" scroll="no">
    <div region="west" split="true" title="产品结构树" style="width: 180px;" id="west">
        <ul id="tree">
        </ul>
    </div>
    <div region="center" style="width: 500px; height: 300px; padding: 1px; background: #eee;
        overflow-y: hidden">
        <div id="grid" fit="true">
        </div>
    </div>
    <div id="eidt-window" title="编辑窗口" style="width: 350px; height: 200px;">
        <div style="padding: 20px 20px 40px 80px;">
            <form method="post">
            <table>
                <tr>
                    <td>
                        名称:
                    </td>
                    <td>
                        <input name="title" style="width: 150px;" />
                    </td>
                </tr>
            </table>
            </form>
        </div>
        <div style="text-align: center; padding: 5px;">
            <a href="javascript:void(0)" onclick="saveData()" id="btn-save" icon="icon-save">保存</a>
            <a href="javascript:void(0)" onclick="closeWindow()" id="btn-cancel" icon="icon-cancel">
                取消</a>
        </div>
    </div>
    <div id="search-window" title="查询窗口" style="width: 350px; height: 200px;">
        <div style="padding: 20px 20px 40px 80px;">
            <form method="post">
            <table>
                <tr>
                    <td>
                        名称:
                    </td>
                    <td>
                        <input name="s_title" id="s_title" style="width: 150px;" />
                    </td>
                </tr>
            </table>
            </form>
        </div>
        <div style="text-align: center; padding: 5px;">
            <a href="javascript:void(0)" onclick="SearchOK()" id="btn-search" icon="icon-ok">确定</a>
            <a href="javascript:void(0)" onclick="closeSearchWindow()" id="btn-search-cancel" icon="icon-cancel">
                取消</a>
        </div>
    </div>
</body>

主要js代码:

代码Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->$(function () {

    $('#btn-save,#btn-cancel').linkbutton();
    win = $('#eidt-window').window({
        closed: true,
        modal: true,
        shadow: false
    });
    form = win.find('form');

    $('#btn-search,#btn-search-cancel').linkbutton();
    searchWin = $('#search-window').window({
        closed: true,
        modal: true
    });
    searchForm = searchWin.find('form');

    tree = $('#tree').tree({
        checkbox: false,
        url: 'GetClassJsonByPid.ashx?pid=0',
        onBeforeExpand: function (node, param) {
            //alert(node.id);
            $('#tree').tree('options').url = "GetClassJsonByPid.ashx?pid=" + node.id; // change the url                       
            //param.myattr = 'test';    // or change request parameter
        },
        onClick: function (node) {
            clickTree(node.id);
        }
    });

    grid = $('#grid').datagrid({
        title: '产品管理',
        iconCls: 'icon-save',
        url: 'Handler.ashx?action=list',
        sortName: 'ID',
        sortOrder: 'desc',
        idField: 'ID',
        pageSize:30,
        frozenColumns: [[
                    { field: 'ck', checkbox: true }
                    //,{ title: 'ID', field: 'ID', width: 80, sortable: true }
                ]],
        columns: [[
                    { field: 'title', title: '名称', width: 150 },
                    { field: 'addTime', title: '添加日期', width: 150, sortable: true }
                ]],
        pagination: true,
        rownumbers: true,
        singleSelect: false,
        toolbar: [{
            text: '新增',
            iconCls: 'icon-add',
            handler: add
        }, '-', {
            text: '修改',
            iconCls: 'icon-edit',
            handler: edit
        }, '-', {
            text: '删除',
            iconCls: 'icon-remove',
            handler: del
        }, '-', {
            text: '查找',
            iconCls: 'icon-search',
            handler: OpensearchWin
        }, '-', {
            text: '所有',
            iconCls: 'icon-search',
            handler: showAll
        }]
    });
    $('body').layout();
});

var tree;
var grid;
var win;
var form;
var searchWin;
var searchForm;

function clickTree(nodeid) {
    grid.datagrid({ url: 'Handler.ashx?action=list&PID=' + nodeid });
    grid.datagrid('clearSelections');
}

function getSelectedArr() {
    var ids = [];
    var rows = grid.datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].ID);
    }
    return ids;
}
function getSelectedID() {
    var ids = getSelectedArr();
    return ids.join(',');
}
function arr2str(arr) {
    return arr.join(',');
}

function add() {
    win.window('open');
    form.form('clear');
    form.url = 'Handler.ashx?action=save';
}
function edit() {
    var rows = grid.datagrid('getSelections');
    var num = rows.length;
    if (num == 0) {
        $.messager.alert('提示', '请选择一条记录进行操作!', 'info');
        return;
    }
    else if (num > 1) {
        $.messager.alert('提示', '您选择了多条记录,只能选择一条记录进行修改!', 'info');
        return;
    }
    else{
        win.window('open');
        form.form('load', 'Handler.ashx?action=get&id=' + rows[0].ID);
        form.url = 'Handler.ashx?action=save&id=' + rows[0].ID;
    }
}
function del() {
    var arr = getSelectedArr();
    if (arr.length>0) {
        $.messager.confirm('提示信息', '您确认要删除吗?', function (data) {
            if (data) {
                $.ajax({
                    url: 'Handler.ashx?action=del&id=' + arr2str(arr),
                    type: 'GET',
                    timeout: 1000,
                    error: function () {
                        $.messager.alert('错误', '删除失败!', 'error');
                    },
                    success: function (data) {
                        eval('data=' + data);
                        if (data.success) {
                            grid.datagrid('reload');
                            grid.datagrid('clearSelections');
                        } else {
                            $.messager.alert('错误', data.msg, 'error');
                        }
                    }
                });
            }
        });
    } else {
        $.messager.show({
            title: '警告',
            msg: '请先选择要删除的记录。'
        });
    }
}

function showAll() {
    grid.datagrid({ url: 'Handler.ashx?action=list' });
}
function OpensearchWin() {
    searchWin.window('open');
    searchForm.form('clear');
}

function saveData() {
    form.form('submit', {
        url: form.url,
        success: function (data) {
            //alert(data);
            eval('data=' + data);
            if (data.success) {
                grid.datagrid('reload');
                win.window('close');
            } else {
                $.messager.alert('错误', data.msg, 'error');
            }
        }
    });
}
function closeWindow() {
    win.window('close');
}

function SearchOK() {
    var s_title = $("#s_title").val();
    searchWin.window('close');
    grid.datagrid({ url: 'Handler.ashx?action=query', queryParams: {title: s_title} });
}
function closeSearchWindow() {
    searchWin.window('close');
}

取树结构数据的后台处理程序GetClassJsonByPid.ashx代码如下:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
using System;
using System.Web;
using System.Data;

public class GetClassJsonByPid : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string sJsonTree = string.Empty;
        int parentId = -1;
        string pid = context.Request.QueryString["pid"];
        if (!string.IsNullOrEmpty(pid))
            Int32.TryParse(pid, out parentId);
        if (parentId>=0)
            sJsonTree = getJsonTree(parentId);
        context.Response.Write(sJsonTree);
    }
    public string getJsonTree(int pid)
    { 
        string resultStr = "";
        resultStr += "[";
        string sqlexe = @"select * From proclass where pid=" + pid.ToString() + " order by [Order] ASC";
        DataTable dt = mdb.db.GetDataTable(sqlexe);
        foreach (DataRow dr in dt.Rows)
        {
            string id = dr["id"].ToString();
            string state = "open";
            if (bChild(id))
                state = "closed";
            resultStr += "{";
            resultStr += string.Format("\"id\": \"{0}\", \"text\": \"{1}\", \"iconCls\": \"\", \"state\": \"" + state + "\"", dr["id"].ToString(), dr["Name"].ToString());
            resultStr += "},";
        }
        resultStr = resultStr.Substring(0, resultStr.Length - 1);                   
        resultStr += "]";
        return resultStr;
    }
    public Boolean bChild(string pid)
    {
        string sqlexe = @"select * From proclass where pid=" + pid.ToString() + " order by [Order] ASC";
        DataTable dt = mdb.db.GetDataTable(sqlexe);
        return dt.Rows.Count > 0;
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}

及DataGrid相关处理后台页面Handler.ashx代码如下:

using System.Web;
using System.Text;
using System.Data;
using System.Data.OleDb;
public class Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string sReturnJson = string.Empty;
        string sqlexe = string.Empty;
        string action = ParamsofEasyUI.RequstString("action");
        switch (action)
        {
            case "save":
                sReturnJson = save();
                break;
            case "del":
                sReturnJson = delete();
                break;
            case "list":
            case "query":
                sReturnJson = getData(action);
                break;
            case "get":
            sReturnJson=getSingleData();
                break;
            default:
                break;
        }
        context.Response.Write(sReturnJson);
    }

    private string getSingleData()
    {
        string id = ParamsofEasyUI.RequstString("id");
        string sqlexe = @"select ID,title,addTime from product where id=" + id + "";
        DataTable dt = mdb.db.GetDataTable(sqlexe);
        return Json4EasyUI.onForm(dt);
    }
    private string getData(string action)
    {
        string order = ParamsofEasyUI.order;
        string sort = ParamsofEasyUI.sort;
        int page = ParamsofEasyUI.page;
        int rows = ParamsofEasyUI.rows;
        
        string sWhere = string.Empty;
        string sqlexe = string.Empty;
        if (action.Equals("list"))
        {
            string PID = ParamsofEasyUI.RequstString("PID");
            if (!string.IsNullOrEmpty(PID))
            {
                sWhere = " where [parent]=" + PID;
                page = 1;
            }
        }
        else if (action.Equals("query"))
        {
            string stitle = ParamsofEasyUI.RequstString("title");
            if (!string.IsNullOrEmpty(stitle))
                sWhere = " where title like '%" + stitle + "%'";
        }
        //sqlexe = @"select top 10 ID,title,addTime from (select top 20 * from product " + PID + " order by [addTime] DESC,ID desc) as a";
        sqlexe = @"select ID,title,addTime from product " + sWhere + " order by " + sort + " " + order + ",ID desc";
        DataTable dt = mdb.db.GetDataTable(sqlexe);
        return Json4EasyUI.onDataGrid(dt, page, rows);
    }
    private string delete()
    {
        string sReturnJson = string.Empty;
        string id = ParamsofEasyUI.RequstString("id");
        string sqlexe = string.Format("delete from product where id in ({0})", id);
        if (mdb.db.ExecuteUpdate(sqlexe))
            sReturnJson = "{success:true}";
        else
            sReturnJson = "{success:false}";
        return sReturnJson;
    }
    private string save()
    {
        string sReturnJson = string.Empty;
        string id = ParamsofEasyUI.RequstString("id");
        string title = ParamsofEasyUI.RequstForm("title");
        string sqlexe = string.Empty;
        if (id.Length > 0)
        {
            sqlexe = "update product set title=@title where id=@id";
            OleDbParameter[] param = {
                new OleDbParameter("@title",title),
                new OleDbParameter("@id",Convert.ToInt32(id))
                };
            if (mdb.db.ExecuteNonQuery(sqlexe, param) == 0)
                sReturnJson = "{success:false}";
            else
                sReturnJson = "{success:true}";
        }
        else
        {
            sqlexe = string.Format("insert Into product (title,addtime) values ('{0}','{1}')",
               title, System.DateTime.Now.ToString());
            if (mdb.db.ExecuteUpdate(sqlexe))
                sReturnJson = "{success:true}";
            else
                sReturnJson = "{success:false,msg:'删除信息失败'}";
        }
        return sReturnJson;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

相关推荐