JQuery使用Datatable插件(二)——使用AJAX与后端交互

一、html代码(我自定义了一个搜索框,同时用到了bootstrap框架)

注意引入相应文件,同时table一定要有thead

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Datatable利用ajax增删改查</title>
<!-- 引入datatable的css样式文件和bootstrap的css样式文件 -->
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/views/admin/css/jquery.dataTables.css">
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/views/admin/css/bootstrap.css">
<!--  引入jquery.js和datatable、bootstrap的js文件-->
<script type="text/javascript" src="${pageContext.request.contextPath}/views/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/views/admin/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/views/admin/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/views/admin/js/myDatatable.js"></script>
</head>
<body>
<!--  自定义搜索框-->
<form class="form-inline form-horizontal">
     <div class="form-group text-center" style="padding-top:20px">
         <label for="search">关键字</label>
         <input type="text" id="search" name="search">
         <button type="button" class="btn btn-primary" id="searchBtn">查询</button>
     </div>   
 </form>
 <!--  表格-->
 <table id="myDatatable" style='margin-bottom:0;text-align: center'>
      <thead>
          <tr>
              <th><input type="checkbox" id="checkAll" name="checkAll" /></th>
              <th>
                  ID
              </th>
              <th>
                  用户名
              </th>
              <th>
                  用户头像
              </th>
              <th>
                  联系电话
              </th>
              <th>
                  邮箱
              </th>
              <th>
                  创建时间
              </th>
              <th>
                  状态
              </th>
              <th>
                  操作
              </th>
          </tr>
      </thead>
      <tbody>
               
      </tbody>
  </table>
</body>
</html>

二、实现datatable的myDatatable.js文件

注意:

1.与后台交互必须设置"serverSide": true,//启用服务端分页(这是使用Ajax服务端的必须配置)

2.设置列时,必须跟后台传来的数据名保持一致(null代表没有对应数据),需要特别操作时给数据绑定函数,
 "render":function (data, type, full, meta),其中的data就是对应列从后台传来的数据,直接使用即可

/**
	 * DataTable属性配置以及生成datatable
	 */	
	    $('#myDatatable').DataTable({
	    	"select": true,
	        "processing": true,//数据加载时显示进度条
	        "serverSide": true,//启用服务端分页(这是使用Ajax服务端的必须配置)
	        "searching": false,//是否启用搜索功能
	        "ajax": {//ajax请求后台
		        "url": "/booking/admin/showPage",
		        "type": "POST",
		        "data": function (d) {
		            d.pageNo = $("#myDatatable").DataTable().page();//获取当前页码
		            var key = $("#search").val();//获取搜索框关键字
		            d.extraSerach=key;//查询条件
		        }
		    },
	        "columns": [
	        	/**
	        	 * 设置列,必须跟后端传来的数据名保持一致(null代表没有对应数据),需要特别操作时给数据绑定函数,
	        	 * "render":function (data, type, full, meta),其中的data就是对应列从后台传来的数据,直接使用即可
	        	 */
	        	{"data":"null","render":function (data, type, full, meta) {
		            return "<td> <input type='checkbox' name='checkbox' class='checkboxes' /><td>";
		        }},
	            {"data": "uid"},
	            {"data": "uname"},
	            {"data": "uicon","render":function (data, type, full, meta){
	            	if(data){
	            		var content="<td><img width='60px' height='60px' src=/booking/views/admin/images/userIcon/"+data+"></td>";
	            	}else{
	            		var content="<td><img width='60px' height='60px' src='#'></td>";
	            	}
		            return content;
	            }},
	            {"data": "telephone"},
	            {"data": "email"},
	            {"data": "create_time"},
	            {"data": "enable","render":function (data, type, full, meta) {
	            	var content="";
	            	if(data){
	            		content+="<td><span class='label label-success'>有效</span></td>";
	            	}else{
	            		content+="<td><span class='label label-default'>无效</span></td>";
	            	}
		            return content;
		        }},
	            {"data": "enable","render":function (data, type, full, meta) {
	            	var content="<td> <div>";
	            	if(data){
	            		content+="<a class='btn btn-warning btn-mini' onclick='fnChangeAble(this)'><i class='fa fa-times-circle' aria-hidden='true''>禁用</i></a>";
	            	}else{
	            		content+="<a class='btn btn-success btn-mini' onclick='fnChangeAble(this)'><i class='fa fa-check-circle' aria-hidden='true''>启用</i></a>";
	            	}
	            	content+="<a class='btn btn-primary  btn-mini' onclick='fnEdit(this)'><i class='fa fa-cog' aria-hidden='true''>编辑</i></a>";
	            	content+="<a class='btn btn-danger  btn-mini' onclick='fnDelete(this)'><i class='fa fa-trash' aria-hidden='true'>删除</i></a>";
	            	content+="</div></td>";
	            	return content;
		        }},
	        ],
	        "info":true, //分页信息提示等等
	        "paging":   true,//是否分页
	        "pagingType":   "full_numbers",//分页按钮有首页、上一页、下一页、尾页、页码
	        "bLengthChange": true, //开关,是否显示每页显示多少条数据的下拉框
	        "aLengthMenu": [[2, 3, 5], [2, 3, 5]],//设置每页显示数据条数的下拉选项
	        'iDisplayLength': 2, //每页初始显示5条记录
	        'bFilter': false,  //是否使用内置的过滤功能(是否去掉搜索框)
	        "bSort": false, //是否可排序
	        //"aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0 ] }],//进制某列排序
	       // "aaSorting": [[1, "asc"]],//指定某列按照什么规则排序
	        "oLanguage":{  //将英文信息转换未中文
	            "sProcessing": "处理中...",
	            "sLengthMenu": "显示 _MENU_ 项结果",
	            "sZeroRecords": "没有匹配结果",
	            "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
	            "sInfoEmpty": "显示第 0 至 0 项结果,共 0 项",
	            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
	            "sInfoPostFix": "",
	            "sSearch": "搜索:",
	            "sUrl": "",
	            "sEmptyTable": "表中数据为空",
	            "sLoadingRecords": "载入中...",
	            "sInfoThousands": ",",
	            "oPaginate": {
	            "sFirst": "  首页  ",
	            "sPrevious": "  上一页  ",
	            "sNext": "   下一页  ",
	            "sLast": "  末页  "
	            },
	            "oAria": {
	            "sSortAscending": ": 以升序排列此列",
	            "sSortDescending": ": 以降序排列此列"
	            }
	        }
	    });
	    
	    /**
	     * 全选和全不选
	     */
	    $('#checkAll').change(function () {
		    var checked = $(this).prop("checked");
		    $("input[name='checkbox']").each(function() {
		    	$(this).prop("checked", checked);
		    });
		}); 
	    /**
	     * 获取搜索框关键字并将其写进datatable中的key中
	     */
	    $("#searchBtn").click(function(){
	    	var key = $("#search").val();
	    	var table = $('#myDatatable').DataTable();
	        table.search(key).draw();//将查询关键字写进datatable的key中
	    });

三、后台代码,使用了springmvc(需要接收当前页pageNo、页长度length、简单变量draw、自定义搜索的关键字extraSerach)

实体类user.java

@Entity
@Table(name="t_user")
public class User {
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long uid;
	private String uname;
	@Size(min=128)
	private String upassword;
	private String salt;
	private Boolean enable=false;
	private String uicon="/views/images/avatar/default_avatar.png";
	@Size(min=11,max=11)
	private String telephone;
	private String email;
	@DateTimeFormat(pattern="yy/MM/dd HH:mm:ss")
	@JsonFormat(pattern="yy/MM/dd HH:mm:ss")
	@Column(columnDefinition="timestamp default current_timestamp comment '创建时间'") 
	private Date create_time=new Date();
	private Integer type=0;//0管理员 1用户管理员 2普通用户
	
	@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JsonBackReference
	private Set<Order> orders = new HashSet<Order>();//设置双向关联订单
	
	public Set<Order> getOrders() {
		return orders;
	}
	
	public void setOrders(Set<Order> orders) {
		this.orders = orders;
	}
	
	public Long getUid() {
		return uid;
	}
	public void setUid(Long uid) {
		this.uid = uid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getUpassword() {
		return upassword;
	}
	public void setUpassword(String upassword) {
		this.upassword = upassword;
	}
	public String getSalt() {
		return salt;
	}
	public void setSalt(String salt) {
		this.salt = salt;
	}
	public Boolean getEnable() {
		return enable;
	}
	public void setEnable(Boolean enable) {
		this.enable = enable;
	}
	public String getUicon() {
		return uicon;
	}
	public void setUicon(String uicon) {
		this.uicon = uicon;
	}
	public String getTelephone() {
		return telephone;
	}
	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getCreate_time() {
		return create_time;
	}
	public void setCreate_time(Date create_time) {
		this.create_time = create_time;
	}
	public Integer getType() {
		return type;
	}
	public void setType(Integer type) {
		this.type = type;
	}
	@Override
	public String toString() {
		return "User [uid=" + uid + ", uname=" + uname + ", upassword=" + upassword + ", salt=" + salt + ", enable="
				+ enable + ", uicon=" + uicon + ", telephone=" + telephone + ", email=" + email + ", create_time="
				+ create_time + ", type=" + type + "]";
	}
	
}

controller.java

/**
	 * 实现管理员分页、查询管理
	 * @param pageNo 当前页
	 * @param length 每页的长度
	 * @param draw 没有特别作用,前台传来什么就返回什么,没有则返回1
	 * @param extraSerach 查询条件,实现模糊查询
	 * @return
	 */
	@PostMapping(value="showPage")
	public @ResponseBody String showPage(@RequestParam Integer pageNo,Integer length,Integer draw,String extraSerach) {
		UserDTO queryDto = new UserDTO();
		queryDto.setKey(extraSerach);//查询条件
		PageRequest pageable = PageRequest.of(pageNo, length, Direction.ASC, "uid");//分页条件
		Page<User> userPage = userService.findAll(UserDTO.getSpecification(queryDto), pageable);
		HashMap<String, Object> result = new HashMap<>();
		List<User> data = new ArrayList<User>();
		result.put("data", data);//用户数据
		result.put("draw", draw);//前端传来什么就返回什么,如果没有就返回1
		result.put("recordsTotal", userPage.getTotalElements());//总记录数
		result.put("recordsFiltered", userPage.getTotalElements());//查询过滤后的总记录数,跟recordsTotal保持一致,前台会根据数据自动进行显示
		ObjectMapper jsonObject = new ObjectMapper();
		String json = null;
		try {
			json = jsonObject.writeValueAsString(result);//将所有数据转化成json字符串
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}

查询辅助类UserDTO.java的代码

@Component
public class UserDTO {
	private String key;
	
	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * 自定义查询条件实现模糊查询
	 * @param queryDto 查询工具对象,接收查询条件
	 * @return 返回拼接好的条件
	 */
	@SuppressWarnings("serial")
	public static Specification<User> getSpecification(UserDTO userDTO){
		return new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				//组装查询条件
				if(userDTO.getKey()!=null) {
					Predicate p1 = criteriaBuilder.like(root.get("uname").as(String.class), "%"+userDTO.getKey()+"%");
					Predicate p2 = criteriaBuilder.like(root.get("telephone").as(String.class), "%"+userDTO.getKey()+"%");
					Predicate p3 = criteriaBuilder.like(root.get("email").as(String.class), "%"+userDTO.getKey()+"%");
					Predicate p4 = criteriaBuilder.like(root.get("create_time").as(String.class), "%"+userDTO.getKey()+"%");
					predicates.add(p1);
					predicates.add(p2);
					predicates.add(p3);
					predicates.add(p4);
				}
				return criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()]));//用or拼接查询条件
			}
		};
	}
}

四、最后,来一张效果图

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页