tp5 layui 用JS方法渲染表格table
未知
2023-09-14 13:52:46
0

问题描述:


在tp5框架中使用layui的方法渲染方式制作表格。用JS方法的配置完成渲染。


解决办法:

php:


public function index(){  
    if(request()->isPost()){
        $limit=input("?post.limit")?input('post.limit'):20;
        $page=input("?post.page")?input('post.page'):1;         

        $list = Db::name("order")->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();
        foreach ($list['data'] as $key => &$value) {
            $value['username']=getUserName($value['user_']);
        }
       // 内置循环each()
        //$list = Db::name("order")->paginate(['list_rows'=>$limit,'page'=>$page])
        ->each(function($item, $key) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);                    
                return $item;
        })->toArray();


        return json(['code'=>0,'msg'=>'','count'=>$list['total'],'data'=>$list['data']]);
   }      
   return view();
}

//整合参数,如果$data出现预定义字符就需要使用htmlspecailchars_decode解码。

   //执行修改
    public function update(){
        if(request()->isPost()){
            $json_para = (array)json_decode(htmlspecialchars_decode(input('val')), true);
            $request_m = array();                    
            //调用model类写入数据库
            $mm=Db::name('member')->update($request_m);
            if($mm!=0){
                return json(['code'=>1000,'msg'=>'修改成功']);
            }else {
                return json(['code'=>1001,'msg'=>'更新数据失败']);
            }
        }
    }

html:


   <button type="button" class="layui-btn layui-btn-sm" id="delall" />批量删除</button>
   <script type="text/html" id="toolbarDemo">
          <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="getCheckData">已返款</button>
            <button class="layui-btn layui-btn-sm" lay-event="delBrokerage">批量删除</button>
          </div>
    </script>
     <div class="fl ss_ctr">
       <div class="layui-input-inline" >
           <input type="text" id="keys" class="layui-input" placeholder="用户名/手机号/昵称" >
        </div>               
        <button class="layui-btn layui-btn-sm" id="search" />查询</button>
     </div>
    <div class="layui-ctt">
        <table class="layui-table" id="demo"></table>
    </div>
         //开关
      <script type="text/html" id="status">
        <input type="checkbox" name="switch" id="{{d.id}}"  {{#  if(d.status ==1){ }}
         checked value='2'
        {{#  } else { }}
         value='1'
        {{#  } }} lay-skin="switch" lay-filter="tai" lay-text='正常|禁用'>

    </script>
<script type="text/html" id="shenhe">
    <div class="layui-btn-group">                                
        <button type="button" class="layui-btn layui-btn-sm {{#  if(d.status ==1){ }} layui-btn-normal {{#  } }}" lay-event="shenhe" val='1' >未审核</button>
        <button type="button" class="layui-btn layui-btn-sm {{#  if(d.status ==2){ }} layui-btn-normal {{#  } }}" lay-event="shenhe" val='2' >审核中</button>
        <button type="button" class="layui-btn layui-btn-sm {{#  if(d.status ==3){ }} layui-btn-normal {{#  } }}" lay-event="shenhe" val='3' >返款</button>
    </div>                    
</script>
    <script type="text/html" id="add_date">
        {{#  if(d.add_date !=''){ }}
          {{layui.util.toDateString(d.add_date*1000, 'yyyy-MM-dd HH:mm:ss')}}
        {{#  } }}
    </script>
    <script type="text/html" id="action">
        <a  class="layui-btn layui-btn-sm layui-btn-success" lay-event='handle'>处理</a>
         <a  class="layui-btn layui-btn-sm layui-btn-danger" lay-event="del">删除</a>      
    </script>
    <script type="text/html" id="update_div">
        <form>
            <input type="" name="" id="username">
        </form>      
    </script>
    <script>

        layui.use(['table','form'], function(){
            var table = layui.table,form=layui.form;
            var tableIn = null;
            tableIn=table.render({
                elem: '#demo'
                ,url:"/admin/cnt/urank"
                ,method:"post"
                ,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板。右侧内置打印下载也会开启
                ,page:{
                    limit:20
                    ,limits:[20,30,50,100]
                    ,layout:['count','prev','page','next','refresh']
                    ,groups:10
                }
                ,cols:[[
                    {field:'oid',title:'订单编号',sort:true,fixed:'left', edit: 'text',width:100, style:'border: 1px solid #009688;background-color:#fff '}                
                    ,{field:'add_date',title:'添加时间',templet:'#add_date'}
                    ,templet: function (d) {
                        return '<div ><img src="'+d.picpath+'" alt="" width="50px" height="50px" onclick="showBigImage(this)"></a></div>';
                    }}
                   ,{title:'审核状态',templet:'#status',width:250}
                    {title:'操作',templet:'#action',width:100}

                ]]
            });
            //监听开关事件
            form.on('switch(tai)',function(data){
               val=data.elem.value;
               id=data.elem.id;
               currs=$(".layui-laypage-em").next().html(); //当前页码值
               $.ajax({
                 url:"{:url('admin/updateCheck')}",
                 type:"post",
                 data:{'val':val,'id':id},
                 beforeSend:function(){
                    loading=layer.load(1,{shade:[0.4,'#000']});
                 },
                 success:function(data){
                    layer.close(loading);
                    if(data.code==1000){
                        layer.msg(data.msg,{icon:1});
                        tableIn.reload({
                            page:{curr:currs},//查询后点击编辑或者其他行工具跳转到原查询条件
                               
                        })     
                    }else{
                       layer.msg(data.msg,{icon:2});
                    }                        
                 }
             });
         });
              //头工具栏事件
            table.on('toolbar(demo)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);                
                if(checkStatus.data.length<=0){
                    layer.alert('至少选中一个吧!')
                    return false;

                }
                switch(obj.event){
                        case 'getCheckData':
                        var datas = checkStatus.data;
                        currs=$(".layui-laypage-em").next().html(); //当前页码值
                        $.ajax({
                            url:"{:url('yongjin/updateCAll')}",
                            type:"post",
                            data:{val:JSON.stringify(datas)},//传到Php后台,点击查看php代码
                            beforeSend:function(){
                                loading=layer.load(1,{shade:[0.4,'#000']});
                            },
                            success:function(data){
                                console.log(data);
                            }
                        })                       
                        break;                
                        //删除复选的数据
                        case 'delBrokerage':                     
                        layer.confirm('确定要删除这些数据吗?',function(index){
                            loading=layer.load(1,{shade:[0.2,'#ffe']});//加载层
                            $.post("{:url('yongjin/delBrokerageAll')}",{'val':JSON.stringify(datas)},function(res){
                              if(res.code==1000){
                               layer.msg(res.msg, {icon: 1});                                     
                               tableIn.reload({
                                 page:{curr:currs}
                                 ,where:{}
                               })
                              }
                              layer.close(loading);
                              layer.close(index);

                            }
                         );
                      })
                   break;
                };
            });
           //批量删除
         $(document).on('click','#delall',function(){
              var checkStatus = table.checkStatus('demo');        
              rows=checkStatus.data.length;
              if(rows==0){
                layer.msg('请先选择要删除的数据行!', {icon: 2});
                return ;
              }
              //通过循环获取要删除的所有ID集合
              var ids='';
              for(var i=0;i<rows;i++){
                ids += checkStatus.data[i].id+",";
              }
              currs=$(".layui-laypage-em").next().html();//当前页码
              layer.confirm('确定要删除这些数据吗?',function(index){
                loading=layer.load(1,{shade:[0.2,'#ffe']});//加载层
                $.post('/admin/admin/deleteall',
                  {'ids':ids},
                  function(res){
                    console.log(res);
                    if(res.code==1000){
                      layer.msg(res.msg, {icon: 1});                    
                      tableIn.reload({
                        page:{curr:currs}
                        ,where:{}
                      })
                    }
                    layer.close(loading);
                    layer.close(index);
                  }
                );
              })
            })
               //搜索
            $("#search").click(function(){
                keys=$("#keys").val();
                tableIn.reload({
                    page:{  curr:1 },
                    where:{ keys:keys }
                });
            });
              //监听行工具事件(一行数据右侧的编辑、删除等等)
        table.on('tool(test)',function(obj){
          stime=$("#stime").val();
          faultlevel=$("#faultlevel option:selected").val();
          data=obj.data;
          layevent=obj.event;
          currs=$(".layui-laypage-em").next().html(); //当前页码值
          if(layevent=='del'){
              layer.confirm('确定要删除吗?',function(index){
                $.ajax({
                   url:"{:url('admin/del')}"
                   ,type:"post"
                   ,data:{'id':data.id}
                   ,beforeSend:function(){
                     loading=layer.load(1,{shade:[0.3,'#000']})
                   }
                    ,success:function(data){
                        layer.close(loading);
                        if(data.code==1000){
                          layer.msg(data.msg,{icon:1})
                          tableIn.reload({
                             page:{curr:currs}                               
                          })
                        }else{
                          layer.msg(data.msg,{icon:2})

                        }
                    }
                })
            })
                    
        }
        if(layevent=='edit'){
             layer.open({
                title: '修改会员账户'
                ,type: 2
                  ,shadeClose: true
                  ,shade: 0.8
                  ,area: ['60%', '50%']
                  ,btn: ['确认','取消']
                  ,content: '__URL__/editMember?id='+data.mid //iframe的url或者使用 success()
                 // ,content: $('#update_div')/或者使用 success()
              
                  ,yes: function(index, layero){
                    //点击确定按钮回调方法
               
                    //当点击‘确定’按钮的时候,获取弹出层返回的值。callbackdata是iframe页面中js自定义的函数
                    var res = window["layui-layer-iframe" + index].callbackdata();
                    //打印返回的值,看是否有我们想返回的值。
                    fields=JSON.stringify(res); //转为 JSON数组格式
                     $.ajax({
                        url:"__URL__/updateMember",
                        type:"post",
                        data:{'val':fields},
                        beforeSend:function(){
                            loading=layer.load(1,{shade:[0.3,'#000']});
                        },success:function(data){
                        }

                    })
                },
                success(){
                    $("#username").val(data.username)
                }

            })

        }else if(layEvent=='shenhe'){}
                
        });
       //监听单元格编辑
              table.on('edit(openai_table)', function(obj){
                var value = obj.value //得到修改后的值               
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段
                  currs=$(".layui-show .layui-laypage-em").next().html(); //当前页码值
                  fields=JSON.stringify(data);
                $.ajax({
                    type:'post',
                    url:"__URL__/editTable",
                    data:{'val':fields},                 
                    success:function(data){                      
                    }                   
                })
               
              });
    });
  // 图片层显示
    function showBigImage(e) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true, //点击阴影关闭
            area: [ 'auto'], //宽高
            content: "<img src=" + $(e).attr('src') + " height='500' width='500'/>"
        });
    }
</script>
//layevent==edit专用
//iframe,新建文件edit.html,里面是要编辑的内容及callbackdata自定义函数。

<script type="text/javascript" src="__STATIC__/jquery-3.3.1.min.js"></script>
<div class="layui-form-item">
    <label class="layui-form-label">用户姓名:</label>
      <div class="layui-input-inline">
         <input type="text" name="m_u_name" placeholder="请输入用户姓名" value="{$data.u_name}"  class="layui-input">
      </div>
 </div>
<div class="layui-form-item">
    <label class="layui-form-label">是否激活:</label>
   <div class="layui-input-block">
     <input type="checkbox" name="m_work" value="1" {eq name="$data.is_work" value="1"}checked{/eq} lay-skin="switch">
   </div>
</div>
<script>            
   var callbackdata = function () {
    var data = $('form').serializeArray()
    return data;                 
  }
</script>

//layevent==edit专用

行工具事件 修改按钮


<div id="show_editprompt" style="display:none;">
  <form class="layui-form layui_form_padding20" lay-filter="prompt_form">
    <input type="hidden" name="id">
    <div class="layui-form-item">
      <label class="layui-form-label">权重</label>
      <div class="layui-input-block">
        <input type="text" name="weight" value="100" class="layui-input" placeholder="越大越靠前,默认100">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">所属类别</label>
      <div class="layui-input-block">
        <select name="topic_id">
          <option value="">请选择</option>
           {volist name="topic_list" id="vo"}
          <option value="{$vo.id}">{$vo.title}</option>
           {/volist}
        </select>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">模型标题</label>
      <div class="layui-input-block">
        <input type="text" name="title"  class="layui-input" placeholder="示例:编">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label"></label>
      <div class="layui-input-inline">
        <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="btn_submit">提交</button>
      </div>
    </div>
  </form>
</div>
<script type="text/html" id="action">
    <div class="layui-btn-group">
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
      <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    </div>
    
  </script>
// 每行工具条
table.on("tool(prompt_table)",function(obj){
    var layEvent=obj.event;
    var data=obj.data;

    if(layEvent=='edit'){
     layer.open({
      type: 1,
      title: '修改模型',
      closeBtn: 0,
      shadeClose: true,
      area: ['60%','90%'],   
      content: $("#show_editprompt").html(),
      success:function(layero,index){
        form.render();
        //给表单赋值//prompt_table 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
        form.val("prompt_form", {
          "weight": data.weight
          ,"title": data.title
          ,"desc": data.desc
          ,"topic_id": data.topic_id
          ,"id": data.id
        });        

        //获取表单区域所有值
        // var data1 = form.val("prompt_form");
        // console.log(data1)      
      }
    });       
  }
})
form.on("submit(btn_submit)",function(obj){})


相关内容

MySQL变量的生命周期管...
MySQL变量管理关键在于生命周期控制。需了解全局、会话及用户自定...
2024-11-20 20:46:37
MySQL变量类型与用途
MySQL支持多种数据类型,包括数值、字符串、日期和时间等类型,以...
2024-11-20 20:23:37
MySQL变量的作用域与访...
摘要: MySQL变量具有作用域和访问控制,局部变量限于特定上下...
2024-11-20 20:00:40
MySQL变量定义与初始化
MySQL变量分为系统变量和用户定义变量,用于存储数据和配置参数。...
2024-11-20 19:00:42
如何使用MySQL变量进行...
本文详细介绍了MySQL中用户定义变量、系统变量和局部变量的使用方...
2024-11-20 18:46:45
动态分配MySQL变量的示...
MySQL中,变量用于存储临时数据,包括全局和会话变量以及用户定义...
2024-11-20 18:23:38

热门资讯

JavaScript获取当前协... JavaScript获取当前协议,域名,路径
解决Phpcms V9手机门户... 第一步:开启手机网站。位置:模块 》手机门户 》 添加手机站点,如果模块里面没有手机门户,那么就在模...
layui tooltip提示... 在layui表单中,我们想把一个标签做出提示,以标明这个表单元素是做什么有什么功能时,就可以用上提...
layui中出错Unexpec... layui中出错Unexpected identifier
如何在html中禁止复制文字 问题描述: 如何禁止别人复制自己的文章? 解决办法: 在body标签中添加以下代码: onconte...
JS实现html打印功能,打印... !DOCTYPE htmlhtmlhead meta charset=utf-8 title打印功能...
bootstrap 图片文字居... 问题描述: 让图片和文字居中显示。 解决办法: !-- style--.navbars img{ m...
bootstrap图片排版布局 问题描述: 在使用bootstrap的时候,出现了这样的问题。 排版对不齐。 解决办法: 通过上图发...
手机端底部定位 问题描述: 需要实现的效果 解决办法: !-- 底部 -- div class=layui-row ...