layui 记录1

  目前所做项目很多控件及其数据表格用到layui,整理一下,以后查阅。

  首先数据表格:

  页面Html代码:

    

 <table id="Table" lay-filter="layfilter" ></table>
    <script type="text/html" id="toolbarDemo">
        搜索:
        <div class="layui-inline">
            <input class="layui-input" name="id" id="txtSearch" autocomplete="off">
        </div>
        <button class="layui-btn layui-btn-sm" lay-event="btnSearch">搜索</button>
        <button class="layui-btn layui-btn-sm" lay-event="btnAddNew">添加新</button>
        <button class="layui-btn layui-btn-sm" lay-event="btnDelCheck">删除选中行</button>   
    </script>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

  js代码:

layui.use("table", function () {
    var table = layui.table;
    table.render({
        elem: "#Table"  //页面中的Id
        , id: "ExpertListTableID"   //防止重复id
        , method: "get"
        , url: GetAPIUrl("api/Expert/GetList")
        , where: { "参数": 参数 }  //json传参格式
        , toolbar: "#toolbarDemo"  //头部导航编辑栏 Id
        , title: "标题"
        , page: ListTablePage
        , response: {
            statusCode: "ok" //重新规定成功的状态码为 ok,table 组件默认为 0
        }
        /*, request: {
            pageName: 'curr' //页码的参数名称,默认:page
            , limitName: 'nums' //每页数据量的参数名,默认:limit
        }
        , width: 1024
        , height: 500
        , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据    这个就是后台返回的数据
            return {   //返回数据
                "code": res.status, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.total, //解析数据长度
                "data": res.rows.item //解析数据列表
            };
        }*/
        , cols: [[
            { type: "checkbox", fixed: "left" }
            , { type: "numbers", title: "序号"}
            , { field: "lieming1", title: "列名1", sort: true }
            , { field: "lieming2", title: ""}
            , { field: "lieming3", title: ""}
            , { field: "lieming4", title: ""}
            , { field: "lieming5", title: "" }
            , { field: "lieming6", title: ""}
            , { field: "lieming7", title: "" }
            , { fixed: "right", title: "操作", toolbar: "#barDemo"}
        ]]
    });

    //这里以搜索为例   这是重载table
    //table.reload({
    //    where: {"uid":""} //设定异步数据接口的额外参数
    //    , page: {
    //        curr: 1 //重新从第 1 页开始
    //    }
    //});


    //头工具栏事件
    table.on("toolbar(layfilter)", function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);//获取本页表格所有数据的Id
        switch (obj.event) {
            case "getCheckData":
                var data = checkStatus.data; 
                layer.alert(JSON.stringify(data));
                break;
            case "getCheckLength":
                var data = checkStatus.data;
                layer.msg("选中了:" + data.length + " 个");
                break;
            case "btnSearch":
                //window.location = "ExpertEdit.html?action=add";
                break;
            case "btnAddNew":
                window.location = "ExpertEdit.html?action=add&uid=" + uid;
                break;
            case "btnDelCheck":
                layer.confirm("确定删除选中行么?", function (index) {
                    var data = checkStatus.data;
                    var idStr = "";
                    for (var i = 0; i < data.length; i++) {
                        idStr += data[i].Id + "|";
                    }
                     
                    if (DelByIds(idStr)) {
                        obj.del();
                        layer.close(index);
                    }
                    layer.close(index);
                });
                break;
        };
    });

    //监听行工具事件
    table.on("tool(layfilter)", function (obj) {
        var data = obj.data;//获取选中的数据
        if (obj.event === "del") {
            layer.confirm("确定删除么", function (index) {
                if (DelById(data.Id)) {
                    obj.del();//链接后台  删除方法
                    layer.close(index);
                }
            });
        } else if (obj.event === "edit") {
            window.location = "ExpertEdit.html?action=edit&uid=" + uid + "&eid=" + data.Id;
        } else if (obj.event === "info") {
            window.location = "ExpertInfo.html?action=edit&uid=" + uid + "&eid=" + data.Id;
        }
    });
});

 


//按id删除
function DelById(eid) {
    var b = false;
    $.ajax({
        url: GetAPIUrl("api/Expert/Delete"), //地址
        type: "Delete",
        dataType: "json",
        async: false,
        data: { "uid": uid, "eid": eid },
        success: function (msg) {
            if (msg.code == "ok") {
                b = true;
            }
            else {
                layerAlert(msg.msg);
            }
        },
        error: function () {
            layerErrAlert();
        }
    });
    return b;
}
//id数组删除
function DelByIds(eids) {
    var b = false;
    $.ajax({
        url: GetAPIUrl("api/Expert/BatchDelete"), //地址
        type: "Delete",
        dataType: "json",
        async: false,
        data: { "uid": uid, "eid": eids },
        success: function (msg) {
            if (msg.code == "ok") {
                b = true;
            }
            else {
                layerAlert(msg.msg);
            }
        },
        error: function () {
            layerErrAlert();
        }
    });
    return b;
}

  

 

  编辑页面:

  首先就是页面赋值

  html页面:

<form id="form1" class="layui-form" lay-filter="formFilter">
这里是编辑页面 里面的表单

下面 是上传图片功能
<div class="layui-form-item">
<label class="layui-form-label">照片</label>
<div class="layui-input-block">
<button type="button" class="layui-btn" id="expert_photo_up"><i class="layui-icon">&#xe67c;</i>上传照片</button>
<button type="button" class="layui-btn" id="expert_photo_view">查看照片</button>
<label id="demoText"></label>
<div class="layui-input-inline">
<input type="hidden" id="expert_photo" name="expert_photo" class="layui-input">
</div>
<img class="layui-upload-img" id="photoimg" name="photoimg" style="width:295px;height:413px;display:none">
</div>
</div>

 


</form>

注意 一定要 用form,因为 layui需要form进行渲染

  js页面:

  

layui.use(['form', 'layedit', 'laydate', 'upload'], function () {
    var form = layui.form
        , layer = layui.layer
        , laydate = layui.laydate;
    var upload = layui.upload;

    //上传设置  
    var uploadInst = upload.render({
        elem: '#expert_photo_up' //绑定元素
        , url: GetAPIUrl("api/FileUpload/ImgUpload") //上传接口
        , method: "POST"
        , before: function (obj) {
            //预读本地文件示例,不支持ie8
            obj.preview(function (index, file, result) {
                $('#photoimg').attr('src', result); //图片链接(base64)
            });
        }
        , done: function (msg) {
            if (msg.code == "ok") {
                layer.msg(msg.msg);
                $('#expert_photo').val(msg.url);
                $('#photoimg').attr('src', GetAPIUrl(msg.url));
                //$("#expert_photo_view").click();
            }
            else {
                layerAlert("上传失败!");
            }
        }
        , error: function () {
            //请求异常回调
            //演示失败状态,并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });
//对于日期的渲染 有多少个Id就渲染多少个
    //日期渲染
    laydate.render({
        elem: '#expert_birthdate'
    });
    //日期渲染
    laydate.render({
        elem: '#expert_starttime_quantum'
    });
    //日期渲染
    laydate.render({
        elem: '#expert_endtime_quantum'
    });

    //监听提交
    form.on('submit(btnAddNew)', function (data) {
        var JsonSendData = JSON.stringify(data.field);  //这里是获取页面的数据 
        $.ajax({
            cache: true,
            type: "POST",
            dataType: "json",
            url: , add //这里是地址
            data: {"data": JSON.stringify(data.field) },
            async: false,
            success: function (msg) {
                layerAlert(msg.msg);
            },
            error: function (request) {
                layerErrAlert();
            }
        });
        return false;
    });

//编辑 form.on(
'submit(btnEdit)', function (data) { var JsonSendData = JSON.stringify(data.field); if (JsonSendData != "" && JsonSendData != undefined) { JsonSendData = "{\"Id\":\"" + getQueryString("eid") + "\"," + JsonSendData.substring(1); } $.ajax({ cache: true, type: "PUT", dataType: "json", url: Update, data: { "uid": uid, "data": JsonSendData }, async: false, success: function (msg) { layerAlert(msg.msg); }, error: function (request) { layerErrAlert(); } }); return false; }); //表单初始赋值 首先要获取数据 if (action == "edit") {//修改 $.ajax({ url: GetEntity, //地址 type: "GET", dataType: "json", async: false, data: {"eid": getQueryString("eid") }, //根据Id success: function (msg) { if (msg.code == "ok") { SetFormEntity(form, msg.data[0]); //表单赋值方法 } else { layerAlert(msg.msg); } }, error: function () { layerErrAlert(); } }); //return jsonEntity; } else if (action == "edits") { //修改 $.ajax({ url: GetAPIUrl("api/Expert/GetEntity"), //地址 type: "GET", dataType: "json", async: false, data: { "uid": uid, "eid": getQueryString("eid") }, success: function (msg) { if (msg.code == "ok") { SetFormEntity(form, msg.data[0]); } else { layerAlert(msg.msg); } }, error: function () { layerErrAlert(); } }); //return jsonEntity; } else if (action == "add") {//添加 //return false; } else { //return false; } //form.render(); //监听指定开关 //form.on('switch(switchTest)', function (data) { // layer.msg('开关checked:' + (this.checked ? 'true' : 'false'), { // offset: '6px' // }); // layer.tips('温馨提示:请注意开关状态的文字可以随意定义,而不仅仅是ON|OFF', data.othis) //}); }); //表单初始赋值 这里要注意的是 下面的 红色是Id,要与 html页面中的表单 Id一致。 function SetFormEntity(form, jsonEntity) { form.val('formFilter', { "expert_name": jsonEntity.Expert_name, "expert_idcard": jsonEntity.Expert_idcard, "expert_sex": jsonEntity.Expert_sex, "expert_birthdate": formatDate(jsonEntity.Expert_birthdate), "expert_photo": jsonEntity.Expert_photo, "expert_native_place": jsonEntity.Expert_native_place, "expert_nation": jsonEntity.Expert_nation, "expert_political": jsonEntity.Expert_political, "expert_work_unti": jsonEntity.Expert_work_unti, "expert_duty": jsonEntity.Expert_duty, "expert_title": jsonEntity.Expert_title, "expert_email": jsonEntity.Expert_email, "expert_phone": jsonEntity.Expert_phone, "expert_mobile": jsonEntity.Expert_mobile, "expert_address": jsonEntity.Expert_address, "expert_school": jsonEntity.Expert_school, "expert_specialty_name": jsonEntity.Expert_specialty_name, "expert_education_degree": jsonEntity.Expert_education_degree, "expert_category_name": jsonEntity.Expert_category_name, "expert_field_name": jsonEntity.Expert_field_name, "expert_from_name": jsonEntity.Expert_from_name, "remarks": jsonEntity.Remarks, "expert_starttime_quantum": jsonEntity.Expert_starttime_quantum, "expert_endtime_quantum": jsonEntity.Expert_endtime_quantum, "expert_avoid_entry": jsonEntity.Expert_avoid_entry //"like[write]": true //复选框选中状态 //"close": true //开关状态 }) //图片赋值 $("#photoimg").attr("src", 图片地址) }

 

posted @ 2019-01-22 14:50  小程序员//  阅读(171)  评论(1编辑  收藏  举报