其他分享
首页 > 其他分享> > 数据分析之Ajax(easyui项目的菜单加载与菜单联动操作)

数据分析之Ajax(easyui项目的菜单加载与菜单联动操作)

作者:互联网

首先在PyCharm中创建一个django包
然后完成以下步骤:
在这里插入图片描述
接下来就是创建app——hw_007:
在这里插入图片描述
在数据库里输入以下代码:

DROP DATABASE IF EXISTS tdb;
CREATE DATABASE tdb;
USE tdb;
CREATE TABLE t_user(
id VARCHAR(40) PRIMARY KEY,
username VARCHAR(32),
`password` VARCHAR(255),
NAME VARCHAR(10),
regdate DATETIME,
state INT
)ENGINE=INNODB CHARSET=utf8;
INSERT INTO t_user(id,username,PASSWORD,NAME,regdate,state)VALUES(UUID(),'admin','admin','管理员', NOW(),0 );
INSERT INTO t_user(id,username,PASSWORD,NAME,regdate,state)VALUES(UUID(),'zs','123','张三', NOW(),0 );
INSERT INTO t_user(id,username,PASSWORD,NAME,regdate,state)VALUES(UUID(),'suiyue','suiyue','岁月', NOW(),0 );

CREATE TABLE t_role(
id INT AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(10)
)ENGINE=INNODB CHARSET=utf8;
INSERT INTO t_role(id,NAME) VALUES(1,'超级管理员'),(2,'管理员'),(3,'操作员');

CREATE TABLE t_user_role(
uid VARCHAR(40) NOT NULL,
rid INTEGER NOT NULL
)ENGINE=INNODB CHARSET=utf8;

INSERT INTO t_user_role(uid,rid) SELECT id,2 FROM t_user WHERE username='admin';
INSERT INTO t_user_role(uid,rid) SELECT id,3 FROM t_user WHERE username='zs';

CREATE TABLE t_menu(
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(20) NOT NULL,
url VARCHAR(255),
icon VARCHAR(255),
state INT ,
pid INT
) ENGINE=INNODB CHARSET=utf8;
INSERT INTO t_menu VALUES(1,'系统管理',NULL,NULL,0,0),(11,'参数设置',NULL,NULL,0,1),(12,'数据备份',NULL,NULL,0,1);
INSERT INTO t_menu VALUES(2,'权限管理',NULL,NULL,0,0),(22,'用户管理','user/list',NULL,0,2),(21,'角色管理',NULL,NULL,0,2);
INSERT INTO t_menu VALUES(3,'业务管理',NULL,NULL,0,0),(31,'采购业务',NULL,NULL,0,3),(32,'销售业务',NULL,NULL,0,3);
INSERT INTO t_menu VALUES(311,'采购计划',NULL,NULL,0,31),(312,'采购单据',NULL,NULL,0,31),(313,'采购报表',NULL,NULL,0,31);
INSERT INTO t_menu VALUES(321,'销售计划',NULL,NULL,0,32),(322,'销售单据',NULL,NULL,0,32),(323,'销售报表',NULL,NULL,0,32);

SELECT * FROM t_user;
SELECT * FROM t_role;
SELECT * FROM t_menu;

UPDATE t_menu SET url='/admin/user/ui/list' WHERE id=22;

开始反向生成models.py文件:
在这里插入图片描述
以上步骤完成后就开始代码部分了

commons.py

from datetime import datetime, date
import json


class JsonResult:
    def __init__(self, *, code=0, msg=None, data=None):
        self.code = code
        self.msg = msg
        self.data = data


class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)


class JsonResultUtils:
    @staticmethod
    def fail(*, code=0, msg=None):
        return JsonResult(code=code, msg=msg, data=None)

    @staticmethod
    def success(*, code=1, data=None):
        return JsonResult(code=code, msg=None, data=data)


urls.py

from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
    path('login/',views.login,name='login'),
    path('admin/',include('hw_007.urls'))
]


views.py


import json
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from hw_007.blls import TUserManager
from hw_07 import commons


def login(req):
    if req.method == 'GET':
        return render(req, 'login.html')
    elif req.method == 'POST':
        username = req.POST.get('username', '')
        password = req.POST.get('password', '')
        userManager = TUserManager()
        r = userManager.login(username, password)
        print(r, type(r))
        s = json.dumps(r, cls=commons.CJsonEncoder)
        print(s)
        resp = HttpResponse(s)
        resp['content-type'] = 'application/json;charset=utf-8'
        return resp
blls.py

import math

from hw_007 import models
from hw_07.commons import JsonResultUtils


class TUserManager:
    def __init__(self):
        pass

    def login(self, username, password):
        try:
            user = models.TUser.objects.get(username__exact=username)
            if user.password == password:
                r = JsonResultUtils.success(data={k: v for k, v in user.__dict__.items() if k != '_state'})
            else:
                r = JsonResultUtils.fail(code=-2, msg="密码错误")

        except Exception as e:
            print(e)
            r = JsonResultUtils.fail(code=-1, msg='用户名不存在')
        return r.__dict__

    def list(self, *, page=1, rows=10, **kwargs):
        queryset = models.TUser.objects.all()
        count = queryset.count()
        if rows is None: rows = 10
        if rows < 1: rows = 10
        pageCount = int(math.ceil(count / rows))
        if page < 1: page = 1
        if page > pageCount: page = pageCount
        if page < 1: page = 1

        start = (page - 1) * rows
        end = page * rows
        queryset = queryset[start:end]

        return {
            'total': count,
            'rows': [item for item in queryset.values()]
        }


class TMenuManager:
    def __init__(self):
        pass

    def get_roots(self):
        roots = models.TMenu.objects.filter(pid__exact=0).values()
        return [item for item in roots]

    def __item2vo(self, item):
        result = {
            "id": item['id'],
            "text": item['title'],
            "iconCls": item['icon'],
            "state": item['state'],
        }
        if item.get('url', None) is not None:
            result["attributes"] = {"url": item['url']}
        return result

    def get_items(self, pid):
        result = []
        items = models.TMenu.objects.filter(pid__exact=pid).values()
        for item in items:
            vo = self.__item2vo(item)
            sub = self.get_items(item['id'])
            if sub is not None and len(sub) > 0:
                vo['children'] = sub
            result.append(vo)
        return result


urls.py

from django.urls import path
from . import views

app_name = 'hw_007'
urlpatterns = [
    path('index/', views.index, name='index'),
    path('', views.index),
    path('menu/roots/', views.menu_roots, name="menu_roots"),
    path('menu/items/', views.menu_items, name="menu_items"),
    path('user/list/', views.user_list, name="user_list"),
    path('user/ui/list/', views.user_list_ui, name="user_list_ui"),
]


views.py

import json

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from hw_007 import blls
from hw_07 import commons


def index(req):
    return render(req, 'hw_007/index.html')


def menu_roots(req):
    data = blls.TMenuManager().get_roots()
    jsons = json.dumps(data)
    resp = HttpResponse(jsons)
    resp['content-type'] = 'application/json;charset=utf-8'
    return resp


def menu_items(req):
    id = req.GET.get('id', '')
    data = blls.TMenuManager().get_items(id)
    jsons = json.dumps(data)
    resp = HttpResponse(jsons)
    resp['content-type'] = 'application/json;charset=utf-8'
    return resp


def user_list_ui(req):
    return render(req, 'user/list.html')


def user_list(req):
    page = int(req.GET.get('page', '1'))
    rows = int(req.GET.get('rows', '10'))

    data = blls.TUserManager().list(page=page, rows=rows)
    jsons = json.dumps(data, cls=commons.CJsonEncoder)
    resp = HttpResponse(jsons)
    resp['content-type'] = 'application/json;charset=utf-8'
    return resp

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>学生管理系统--管理后台</title>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static '/libs/jquery-easyui/themes/default/easyui.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static '/libs/jquery-easyui/themes/icon.css' %}">
    <script type="text/javascript" src="{% static '/libs/jquery-3.3.1.js' %}"></script>
    <script type="text/javascript" src="{% static '/libs/jquery-easyui/jquery.easyui.min.js' %}"></script>
</head>

<body class="easyui-layout">
<div data-options="region:'north',title:' ',split:true" style="height:100px;">
    ARE YOU READY ! ! !
</div>
<div data-options="region:'south',title:''" style="height:30px;"></div>
<div data-options="region:'west',title:'系统菜单',split:true" style="width:200px;" id="west">


</div>
<div data-options="region:'center',title:''" style="padding:5px;background:#eee;" id="center">


</div>
<script>
    $(function () {
        $('#west').accordion({
            animate: false
        });
        $.ajax({
            url: "{% url 'hw_007:menu_roots' %}",
            type: 'post',
            data: {'csrfmiddlewaretoken': "{{ csrf_token }}"},
            dataType: 'json',
            success: function (data) {
                //console.log(data)
                if (data && data.length > 0) {
                    $.each(data, function (i, e) {
                        $('#west').accordion('add', {
                            title: e.title,
                            content: '<ul id="m_' + e.id + '" class="easyui-tree" data-options="url:\'{% url 'hw_007:menu_items' %}?id=' + e.id + '\',method:\'get\',anumate:true"></ul>',
                            selected: false
                        });
                        $('#m_' + e.id).tree({
                            onClick: function (node) {
                                if (node.children && node.children.length > 0) return
                                var tabs = $('#center').tabs('tabs')
                                if (tabs.length > 5) {
                                    $.messager.show({
                                        title: '提示',
                                        msg: '同时只能打开6个选项卡',
                                        timeout: 2000,
                                        showType: 'slide'
                                    })
                                    return
                                }
                                var tab = $('#center').tabs('getTab', node.text)
                                if (!tab) {
                                    var options = {
                                        title: node.text,
                                        content: '',
                                        closable: true,
                                        selected: true
                                    }
                                    if (node.attributes && node.attributes.url) {
                                        console.log(node.attributes.url)
                                        options.href = node.attributes.url
                                    }
                                    $('#center').tabs('add', options);
                                } else {
                                    $('#center').tabs('select', node.text);
                                }
                            }
                        });
                    })
                    $('#west').accordion('select', 0)
                }
            }
        })


        $('#center').tabs({
            border: false,
            onSelect: function (title) {

            }
        });
        $('#center').tabs('add', {
            title: '首  页',
            content: '',
            closable: false
        });

    })
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    {% load static %}
    <meta charset="UTF-8">
    <title>学生管理系统--用户列表</title>
    <link rel="stylesheet" type="text/css" href="{% static '/libs/jquery-easyui/themes/default/easyui.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static '/libs/jquery-easyui/themes/icon.css' %}">

    <script type="text/javascript" src="{% static '/libs/jquery-3.3.1.js' %}"></script>
    <script type="text/javascript" src="{% static '/libs/jquery-easyui/jquery.easyui.min.js' %}"></script>
</head>
<body>
<table id="tb"></table>
<script>
    $(function () {
        $('#tb').datagrid({
            url: '{% url "hw_007:user_list" %}',
            method: 'get',
            columns: [[
                {field: 'id', title: 'ID', width: 100, hidden: true},
                {field: 'username', title: '用户名', width: 100},
                {field: 'password', title: '密码', width: 100},
                {field: 'state', title: '状态', width: 100},
                {field: '_opr', title: '操作', width: 50}
            ]]
        });
    })
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    {% load static %}
    <meta charset="UTF-8">
    <title>学生管理系统--登录</title>
    <link rel="stylesheet" type="text/css" href="{% static '/libs/jquery-easyui/themes/default/easyui.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static '/libs/jquery-easyui/themes/icon.css' %}">

    <script type="text/javascript" src="{% static '/libs/jquery-3.3.1.js' %}"></script>
    <script type="text/javascript" src="{% static '/libs/jquery-easyui/jquery.easyui.min.js' %}"></script>
</head>
<body>
<div id="container">
    <div style="margin:20px 0;"></div>
    <div class="easyui-panel" title="用户登录" style="width:400px">
        <div style="padding:10px 60px 20px 60px">
            <form id="ff" cssClass="easyui-form" method="post" action="{% url 'login' %}">
                {% csrf_token %}
                <table cellpadding="5">
                    <tr>
                        <td>用户名:</td>
                        <td><input id="username" name="username" cssClass="easyui-textbox"
                                   data-options="required:true"/></td>
                    </tr>
                    <tr>
                        <td>密码:</td>
                        <td><input type="password" id="password" name="password" cssClass="easyui-textbox"
                                   data-options="required:true"/></td>
                    </tr>
                </table>
            </form>
            <div style="text-align:center;padding:5px">
                <a href="javascript:void(0)" class="easyui-linkbutton" id="btn_ok">登录</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" id="btn_clear">重置</a>
            </div>
        </div>
    </div>
</div>
<script>
    $(function () {


        $('#btn_ok').on('click', function () {
            $('#ff').form({
                'url': "{% url 'login' %}",
                onSubmit: function () {
                    return $(this).form('enableValidation').form('validate')
                },
                success: function (data) {
                    if (typeof (data) == 'string') {
                        data = JSON.parse(data)
                    }
                    if (data.code == 1) {
                        window.location.href = "{% url 'hw_007:index' %}"
                    } else {

                        $.messager.show({
                            title: '提示',
                            msg: data.msg,
                            showType: 'show'
                        });
                    }
                }
            })

            $('#ff').submit()
            return false
        })


        $('#btn_clear').on('click', function () {
            $('#ff').form('reset')
            return false
        })

    })
</script>
</body>
</html>

最后看看实现效果吧
在这里插入图片描述感兴趣的小伙伴自己动手试试吧

标签:菜单,return,easyui,Ajax,user,import,NULL,data,id
来源: https://blog.csdn.net/weixin_66448906/article/details/123084961