[Front-end] Jquery UI +PHP implements table drag sorting

Purpose: Use the jquery ui library to implement drag-and-drop sorting of tables and save the sorting to the database

The effect is as follows

1. Preparation:

1. Download the jquery ui library, you can directly reference the online path

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

2. I use layui for the front end and PHP for the back end.

2. Use

logical explanation

1. Introduce jqueryui library

2. The js code uses the update() method of jqueryui to obtain the dragged item ID and current page number and send them to the background.

3. Since I use thinkphp's paginate for paging in the backend, in order to ensure that the drag and drop sequence on non-first pages can be connected back and forth, the page number is judged. When page=0 or page=1, both page=1, when page is greater than 1, let page=page-1, subtract 1 from the own page number

4. Generate consecutive serial numbers: Set the number of items displayed on each page pageSize (to be consistent with the number of items during paging), multiply the page calculated in step 3 by pageSize, and add 1, for example, page 1: (page*pageSize )+1 => (0*15)+1=1, (0*15)+2=2,... on page 2: (1*15)+1=16, (1*15)+2 =17, the purpose is to enable the new sequence number of the sort entry to be connected during paging, and there will be no need to start from 1 every time you turn a page (the first page: 1, 2, 3,...15, the second page :16, 17...30, third page: 31, 32...)

5. Traverse all entries, add the traversed index value $key based on sort, generate a new serial number for each entry, and finally update the database

front-end code

<table class="layui-table box_table" lay-skin="nob" lay-size="lg" style=" text-align: center;" id="sort">
	<thead>
		<tr>
			<td>课件名</td>
			<td>课件类型</td>
			<td>发送班级</td>
		</tr>
	</thead>
	<tbody>
        <tr>
            <td>内容...</td>
            <td>内容...</td>
            <td>内容...</td>
        </tr>
    </tbody>
</table>

JS code

function GetQueryString(name)
	{
	     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	     var r = window.location.search.substr(1).match(reg);
	     if(r!=null)return  unescape(r[2]); return null;
	}
	// 拖拽排序
	$(document).ready(function () {
		$("#sort tbody").sortable({
			update:function () {
				var idArr = [];
	            $("input[name='id']").each(function() {		//遍历每一行的ID值
	                idArr.push($(this).val());		//把拍完序的数据ID依次推入数组
	            })
	            var page = GetQueryString('page')
	            console.log(idArr)
	            console.log(page)
	            $.ajax({
	                type: "POST",
	                dataType: "json",
	                url: "upsort",
	                data:{idArr:idArr,page:page},
	                success:function (res) {
	                	console.log(res)
	                	layer.msg(res.message, { icon:1, time: 1000 }, function(){
							window.location.reload()
						});
	                },
	                error:function (request) {
	                    console.log(request);
	                }
	            });
	        }
		})
	})

Note: Add id="sort" outside the table, and the selector should select the tbody under the table sort.

backend controller

public function upsort()
	{
		if (request()->isPost()) {

            $data = input('post.');
            $page=$data['page'] ? $data['page']-1 : 0;
            $res = model('Kejian')->upsort($data['idArr'],$page);
            
            if ($res) {
                return apiResponse('200','操作成功');
            }else{
                return apiResponse('110','操作失败');
            }
        }else{
            return apiResponse('110','非法请求');
        }
	}

 Backend model model

public function upsort($idArr,$page)
	{
        $pageSize = 15;     //每页显示条数,与列表分页保持一致
        $sort = ($page * $pageSize)+1;
        Db::startTrans();
        try {
            foreach ($idArr as $key => $value) {
                Db::table('kejian')->update(['id'=>$value,'sort'=>$sort+$key]);
            }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
	}

Guess you like

Origin blog.csdn.net/qq_25285531/article/details/134287545