PHP+ajax+layui实现双重列表的动态绑定

需求:商户下面有若干个门店,每个门店都需要绑定上收款账户

方案一:每个门店下面添加页面,可以选择账户去绑定。(难度:简单)

方案二:从商户进入,可以自由选择门店,以及账户,动态绑定(难度:较复杂)

页面:

        

实现方式,通过选择上面的门店,打勾之后,在选择账户里面的账户,即可实现下面的列表的动态返回,然后点击保存之后,即可将门店和账户的绑定规则传到后台,由后台统一处理

这里页面显示的字符串本来是可以由后台返回,然后js动态拼接的,但是,考虑到js写逻辑过于复杂,操作性不如PHP简易,所以由后台PHP,拼接字符串,然后返回的拼接html代码,直接显示

html代码

{extend name="base" /}
{block name="css"}
<link rel="stylesheet" href="/public/admin/lib/layui/css/layui.css">
<style>
.pic_set_list{width: 100px;display: inline-table;margin-right:10px}
.pic_set_pic{width:100px;float:left}
.pic_set_del{width:100px;float:left}
</style>
{/block}
{block name="body"}
        <div class="layui-fluid">
            <div class="layui-row" style="margin-top:10px">
                <form class="layui-form form-container">
                	<input type="hidden" name="shop_id" id="shop_id" value="{$shop_info['id']}">
					<div class="layui-form-item">
						<label for="L_px" class="layui-form-label">商户</label>
						<div class="layui-input-inline" style="color:red;margin-top: 10px;font-size:16px;">{$shop_info['title']}</div>
					</div>

					<div class="layui-form-item ">
                        <label class="layui-form-label">请选择门店<br>
                        	 <!-- <input type="checkbox" lay-skin="primary" lay-filter="all" name="all" id="all" value="all" title="全选/反选"> -->
                        </label>
                        
                        {foreach name="list" item="vo2"}
                         
                            <input type="checkbox" lay-skin="primary" class="store_check"  name="s_id" value="{$vo2.id}"  title="{$vo2.title}">
            
                        {/foreach}

                    </div>
                    <br>
                    <br>
                    <div class="layui-form-item">
						<label for="L_title_english" class="layui-form-label">账户选择</label>
						<div class="layui-input-inline">
							<select name="province_id" lay-filter="adapay" id="adapay">
								<option value="">请选择账户</option>
								{volist name="adapay" id="v"}
								<option value="{$v['id']}">{$v['name']}</option>
								{/volist}
							</select>
						</div>
					</div>
					<div class="layui-form-item">
						<label for="L_title_english" class="layui-form-label">选择情况</label>
						<div class="layui-input-inline" id="table-data">
							
						</div>
					</div>
					<div class="layui-form-item">
                        <label for="L_repass" class="layui-form-label"></label>
                        <button class="layui-btn" type="reset" id="clean">清空</button>
                        <button class="layui-btn" type="button" id="submit">保存</button>
					</div>
                </form>
            </div>
        </div>
{/block}
{block name="js"}
<script type="text/javascript" src="/public/admin/js/admin.js"></script>
<script type="text/javascript" src="/public/admin/js/xcity.js"></script>
<!-- 配置文件 -->
<script type="text/javascript" src="/public/admin/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="/public/admin/ueditor/ueditor.all.js"></script>
<script type="text/javascript" src="/public/admin/ueditor/lang/zh-cn/zh-cn.js"></script>
{/block}

{block name="script"}
<script>

	//页面第一次进来时候,请求接口,返回已经有的信息
	$(document).ready(function(){
		
		
		var shop_id = $('#shop_id').val();
		$.ajax({
            url:'/admin/shop/return_data2',
            type:'post',
            data:{
                shop_id:shop_id
            },
            dataType:"json",
            success:function(data){
                document.getElementById('table-data').innerHTML = data.data;
            }
        });



		//给特定的函数绑定上删除事件
        $(document).on('click', '.delete_adapay', function() {
        	event.preventDefault();
        	var anchor = $(this).closest('a');
          	// 获取 <a> 标签的参数值
          	var id = anchor.attr('data_id');

          	console.log(id)


          	//获取门店id的多选框的值
			var obj = document.getElementsByName("s_id");
		    var checkList = [];
		    for(k in obj){
		        if(obj[k].checked)
		            checkList.push(obj[k].value);
		    }

		    //获取选择列表中的门店属性值
		    var arr1 = [];
		    $("input[name='title']").each(function(){
	            arr1.push($(this).val());
	        })
	        // console.log(arr1);

	        //获取选择列表中的账户属性值
		    var arr2 = [];
		    $("input[name='adapay']").each(function(){
	            arr2.push($(this).val());
	        })
	        // console.log(arr2);
	        var arr3 = [];
		    $("input[name='ids']").each(function(){
	            arr3.push($(this).val());
	        })
	        // console.log(arr3);


			var adapay = $('#adapay').val();
          	//添加上ajax请求
          	$.ajax({
                url:'/admin/shop/association_del',
                type:'post',
                data:{
                	id:id,
                	adapay:adapay,
                	s_id:checkList,
                	s_id_old:arr1,
                	adapay_old:arr2,
                	ids:arr3
                },
                dataType:"json",
                success:function(data){
                    document.getElementById('table-data').innerHTML = data.data;
                }
            });

    	});


	})


	layui.use('form', function(){
		var form = layui.form;

		layui.form.on('select(adapay)', function(data){

			//获取门店id的多选框的值
			var obj = document.getElementsByName("s_id");
		    var checkList = [];
		    for(k in obj){
		        if(obj[k].checked)
		            checkList.push(obj[k].value);
		    }

		    //获取选择列表中的门店属性值
		    var arr1 = [];
		    $("input[name='title']").each(function(){
	            arr1.push($(this).val());
	        })
	        console.log(arr1);

	        //获取选择列表中的账户属性值
		    var arr2 = [];
		    $("input[name='adapay']").each(function(){
	            arr2.push($(this).val());
	        })
	        console.log(arr2);
	        var arr3 = [];
		    $("input[name='ids']").each(function(){
	            arr3.push($(this).val());
	        })
	        // console.log(arr3);

			var adapay = $('#adapay').val();
			$.ajax({
                url:'/admin/shop/return_data',
                type:'post',
                data:{
                	adapay:adapay,
                	s_id:checkList,
                	s_id_old:arr1,
                	adapay_old:arr2,
                	ids:arr3
                },
                dataType:"json",
                success:function(data){
                    document.getElementById('table-data').innerHTML = data.data;
                }
            });
		})


		$('#clean').click(function(){
			var data = '';
			document.getElementById('table-data').innerHTML = data;

		})



		$('#submit').click(function(){
			var shop_id = $('#shop_id').val();
			var arr1 = [];
		    $("input[name='title']").each(function(){
	            arr1.push($(this).val());
	        })
	        console.log(arr1);

	        //获取选择列表中的账户属性值
		    var arr2 = [];
		    $("input[name='adapay']").each(function(){
	            arr2.push($(this).val());
	        })
	        console.log(arr2);

	        var arr3 = [];
		    $("input[name='ids']").each(function(){
	            arr3.push($(this).val());
	        })

	        $.ajax({
                url:'/admin/shop/associate_save',
                type:'post',
                data:{
                	shop_id:shop_id,
                	s_id_old:arr1,
                	adapay_old:arr2,
                	ids:arr3
                },
                dataType:"json",
                success:function(data){
                	layer.msg(data.msg)
                    window.reload();
                }
            });
		})



	})
</script>
{/block}

后端代码

public function return_data()
    {
        $request = $this->request-> param();
        // dump($request);die; 
        //查询出所要拼接的字符串的项
        $s_ids = $request['s_id'];
        $where['id'] = array('in',$s_ids);
        $store = Db::name('shop_store')->where($where)->select();

        $adapay = Db::name('adapay_user')->where(['id'=> $request['adapay']])->find();

        $string1 = '<div class="layui-card-body layui-table-body layui-table-main">
                                <table class="layui-table">
                                    <thead>
                                        <tr>
                                            <th>门店</th>
                                            <th>账户</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>';
                                        
        $string3 = '</tbody>
                   </table>
                 </div>';


        //对新旧字符串进行处理和分析
        //拼接字符串
        $string2 = '';


        //第一次传值
        if(!isset($request['s_id_old']) && !isset($request['adapay_old'])){
            $id = -1;
            foreach($store as $value){
                
                $string2 = $string2 . '<tr><td><input type="hidden" name="ids" value="'.$id.'" style=" display:none"><input type="text" name="title" value="'.$value["id"].'" style=" display:none">'.$value["title"].'</input></td><td><input type="text" name="adapay" value="'.$adapay["id"].'" style=" display:none">'.$adapay["name"].'</td><td><a href="javascript:(0)" class="layui-btn layui-btns ajax-delete delete_adapay" data_id="'.$id.'" style="background: #e90d24;">删除</a></td></tr>';

                    $id -- ;
            }
        //后续传值
        }else{
            //拼接旧的关联关系
            //如果是新的有,旧的没有的,就直接以新的为标准
            $new_list1=[];

            $min = min($request['ids']);//此时需要将原来的数据都拿过来,然后取最大的,在继续增加变化

            foreach($s_ids as $k => $v){
                if (!in_array($s_ids[$k],$request['s_id_old'])) {
                    $min --;
                    $new_list1['store_id'] =$s_ids[$k];
                    $new_list1['adapay_id'] =$request['adapay'];
                    $new_list1['ids'] =$min;
                    $new_list[] = $new_list1;
                }
                
            }

            //如果两个都有,也就是有需要修改的,会以新的为准
            $new_list2 = [];
            foreach ($s_ids as $key => $value) {
                foreach ($request['s_id_old'] as $key2 => $value2) {
                    
                    if($s_ids[$key] == $request['s_id_old'][$key2]){
                        $new_list2['store_id'] = $request['s_id_old'][$key2];
                        $new_list2['adapay_id'] = $request['adapay'];
                        $new_list2['ids'] = $request['ids'][$key2];
                        $new_list[] = $new_list2;
                        
                    }

                }
            }

            $new_list3 = [];
            //如果是新的没有,旧的有,就按照旧的为准
            foreach ($request['s_id_old'] as $key => $value) {
                if (!in_array($request['s_id_old'][$key],$request['s_id'])) {
                    $new_list3['store_id'] =$request['s_id_old'][$key];
                    $new_list3['adapay_id'] =$request['adapay_old'][$key];
                    $new_list3['ids'] =$request['ids'][$key];
                    $new_list[] = $new_list3;
                }
                 
            }

            foreach ($new_list as $key => $value) {

                $store_info = Db::name('shop_store')->where(['id'=>$new_list[$key]['store_id']])->find();
                $adapay_info = Db::name('adapay_user')->where(['id'=>$new_list[$key]['adapay_id']])->find();
                
                $id = $new_list[$key]['ids'];
                $string2 = $string2 . '<tr><td><input type="hidden" name="ids" value="'.$id.'" style=" display:none"><input type="text" name="title" value="'.$store_info["id"].'" style=" display:none">'.$store_info["title"].'</input></td><td><input type="text" name="adapay" value="'.$adapay_info["id"].'" style=" display:none">'.$adapay_info["name"].'</td><td><a href="#" class="layui-btn delete_adapay ajax-delete" data_id="'.$id.'" style="background: #e90d24;">删除</a></td></tr>';
            }
                
        }




        

        $string = $string1.$string2.$string3;

        $res['code'] = 200;
        $res['data'] = $string;

        $this->ajaxReturn($res);
        
    }

    //修改时候进去,返回已经修改好的情况
    public function return_data2()
    {   
        $request = $this->request-> param();
        $where['shop_id'] = $request['shop_id'];
        $where['is_delete'] = 0;
        $list = Db::name('shop_adapay_user')->where($where)->select();

        $string1 = '<div class="layui-card-body layui-table-body layui-table-main">
                                <table class="layui-table">
                                    <thead>
                                        <tr>
                                            <th>门店</th>
                                            <th>账户</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>';
                                        
        $string3 = '</tbody>
                   </table>
                 </div>';

        $string2 = '';
        foreach ($list as $key => $value) {
            $store_info = Db::name('shop_store')->where(['id'=>$list[$key]['store_id']])->find();
            $adapay_info = Db::name('adapay_user')->where(['id'=>$list[$key]['member_id']])->find();

            $id = $list[$key]['id'];

            $string2 = $string2 . '<tr><td><input type="hidden" name="ids" value="'.$id.'" style=" display:none"><input type="text" name="title" value="'.$store_info["id"].'" style=" display:none">'.$store_info["title"].'</input></td><td><input type="text" name="adapay" value="'.$adapay_info["id"].'" style=" display:none">'.$adapay_info["name"].'</td><td><a href="#" class="layui-btn  delete_adapay ajax-delete" data_id="'.$id.'" style="background: #e90d24;">删除</a></td></tr>';


        }


        $string = $string1.$string2.$string3;

        $res['code'] = 200;
        $res['data'] = $string;

        $this->ajaxReturn($res);
    }

    //保存门店和账户的关联情况
    public function associate_save()
    {
        $request = $this->request-> param();
        // dump($request);die;
        
        $s_id_old = isset($request['s_id_old'])?$request['s_id_old']:[];
        $adapay_old = isset($request['adapay_old'])?$request['adapay_old']:[];
        $num = count($s_id_old);

        for ($i=0; $i < $num; $i++) { 
            $value['shop_id'] = $shop_id;
            $value['store_id'] = $s_id_old[$i];
            $value['member_id'] = $adapay_old[$i];

            //查询出关联的银行卡id
            $where_bank['member_id'] = $adapay_old[$i];
            $where_bank['is_default'] = 1;
            $bank_info = Db::name('shop_account')->where($where_bank)->find();
            if(empty($bank_info)){
                $this->error('请先添加账户对应银行卡!');
            }

            $value['account_id'] = $bank_info['id'];

            $where['shop_id'] = $shop_id;
            $where['store_id'] = $s_id_old[$i];
            $where['is_delete'] = 0;
            //先查询是否有了,有了就修改,没有在插入
            $is_have = Db::name('shop_adapay_user')->where($where)->find();

            if (empty($is_have)) {
                $res = Db::name('shop_adapay_user')->insertGetId($value);
            }else{
                //判断其他字段是否相等,相等就跳过,不相等就去修改
                if($is_have['member_id'] !== $value['member_id'] || $is_have['account_id'] !== $value['account_id']){
                    $res = Db::name('shop_adapay_user')->where(['id'=>$is_have['id']])->update($value);
                }else{
                    $res = true;
                }
            }

        }

        //添加判断,如果是传过来的值没有,但是数据库有,那就删除,修改is_delete为1
        $where_is['is_delete'] = 0;
        $where_is['shop_id'] = $request['shop_id'];
        $list = Db::name('shop_adapay_user')->where($where_is)->select();
        foreach ($list as $key => $value) {
            if(!in_array($list[$key]['store_id'],$request['s_id_old'])){
                $res2 = Db::name('shop_adapay_user')->where(['id'=>$list[$key]['id']])->update(['is_delete'=>1]);
            }
        }

        if($res){
            $this->success('操作成功!');
        }else{
            $this->error('操作失败!');
        }
    }


    //删除功能
    public function association_del()
    {
        $request = $this->request-> param();
        $id_jian = $request['id'];
        // dump($request);die; 
        //查询出所要拼接的字符串的项
        $s_ids = isset($request['s_id'])?$request['s_id']:[];
        $where['id'] = array('in',$s_ids);
        $store = Db::name('shop_store')->where($where)->select();

        $adapay = Db::name('adapay_user')->where(['id'=> $request['adapay']])->find();

        $string1 = '<div class="layui-card-body layui-table-body layui-table-main">
                                <table class="layui-table">
                                    <thead>
                                        <tr>
                                            <th>门店</th>
                                            <th>账户</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>';
                                        
        $string3 = '</tbody>
                   </table>
                 </div>';


        //对新旧字符串进行处理和分析
        //拼接字符串
        $string2 = '';


        //第一次传值
        if(!isset($request['s_id_old']) && !isset($request['adapay_old'])){
            $id = -1;
            foreach($store as $value){
                
                $string2 = $string2 . '<tr><td><input type="hidden" name="ids" value="'.$id.'" style=" display:none"><input type="text" name="title" value="'.$value["id"].'" style=" display:none">'.$value["title"].'</input></td><td><input type="text" name="adapay" value="'.$adapay["id"].'" style=" display:none">'.$adapay["name"].'</td><td><a href="javascript:(0)" class="layui-btn layui-btns ajax-delete delete_adapay" data_id="'.$id.'" style="background: #e90d24;">删除</a></td></tr>';

                    $id -- ;
            }
        //后续传值
        }else{
            //拼接旧的关联关系
            //如果是新的有,旧的没有的,就直接以新的为标准
            $new_list1=[];


            //如果两个都有,也就是有需要修改的,会以新的为准
            $new_list2 = [];
            foreach ($s_ids as $key => $value) {
                foreach ($request['s_id_old'] as $key2 => $value2) {
                    
                    if($s_ids[$key] == $request['s_id_old'][$key2]){
                        $new_list2['store_id'] = $request['s_id_old'][$key2];
                        $new_list2['adapay_id'] = $request['adapay'];
                        $new_list2['ids'] = $request['ids'][$key2];
                        $new_list[] = $new_list2;
                        
                    }

                }
            }

            $new_list3 = [];
            //如果是新的没有,旧的有,就按照旧的为准
            foreach ($request['s_id_old'] as $key => $value) {
                if (!in_array($request['s_id_old'][$key],$s_ids)) {
                    $new_list3['store_id'] =$request['s_id_old'][$key];
                    $new_list3['adapay_id'] =$request['adapay_old'][$key];
                    $new_list3['ids'] =$request['ids'][$key];
                    $new_list[] = $new_list3;
                }
                 
            }

            foreach ($new_list as $key => $value) {

                $store_info = Db::name('shop_store')->where(['id'=>$new_list[$key]['store_id']])->find();
                $adapay_info = Db::name('adapay_user')->where(['id'=>$new_list[$key]['adapay_id']])->find();
                
                $id = $new_list[$key]['ids'];
                if($id !== $id_jian){
                    $string2 = $string2 . '<tr><td><input type="hidden" name="ids" value="'.$id.'" style=" display:none"><input type="text" name="title" value="'.$store_info["id"].'" style=" display:none">'.$store_info["title"].'</input></td><td><input type="text" name="adapay" value="'.$adapay_info["id"].'" style=" display:none">'.$adapay_info["name"].'</td><td><a href="#" class="layui-btn delete_adapay ajax-delete" data_id="'.$id.'" style="background: #e90d24;">删除</a></td></tr>';
                }
                
            }
                
        }

        

        $string = $string1.$string2.$string3;

        $res['code'] = 200;
        $res['data'] = $string;

        $this->ajaxReturn($res);
    }

关联表的数据表结构

可能有其他的办法,我这个也或许不是最优解,因为本该前端处理的dom数据,由PHP处理返回了

另外,如果是前端直接写在页面上的HTML代码,一些,onclick等事件,可以直接绑定,进行监听操作,但是如果是由拼接上的字符串,动态显示的,类似于,富文本内容,则需要加上限定

需要把代码都放在$(document)的后面才能执行,不能直接写js代码

 $(document).on('click', '.delete_adapay', function() {
    //内容
}