基於ssm的考勤設備和考勤記錄管理系統------(三)

1.接着上一篇,寫設備管理的部分

主要界面如下圖

2.這裏面有增刪改查的基本功能,還有分頁的查詢,關鍵詞查詢,還有定時刷新的功能 

實體類如下

package com.timmy.entity;

public class Device {
    private Integer id;

    private String serialNum;

    private String deviceName;

    private String area;

    private Integer status;
    
    private Integer province;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSerialNum() {
        return serialNum;
    }

    public void setSerialNum(String serialNum) {
        this.serialNum = serialNum == null ? null : serialNum.trim();
    }

    public String getDeviceName() {
        return deviceName;
    }

    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName == null ? null : deviceName.trim();
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area == null ? null : area.trim();
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    
	public Integer getProvince() {
		return province;
	}

	public void setProvince(Integer province) {
		this.province = province;
	}

	@Override
	public String toString() {
		return "Device [id=" + id + ", serialNum=" + serialNum
				+ ", deviceName=" + deviceName + ", area=" + area + ", status="
				+ status + "]";
	}
    
}

mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.timmy.mapper.DeviceMapper" >
  <resultMap id="BaseResultMap" type="com.timmy.entity.Device" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="serial_num" property="serialNum" jdbcType="VARCHAR" />
    <result column="device_name" property="deviceName" jdbcType="VARCHAR" />
    <result column="area" property="area" jdbcType="VARCHAR" />
    <result column="status" property="status" jdbcType="INTEGER" />
     <result column="province" property="province" jdbcType="INTEGER" />
  </resultMap>
 
  <sql id="Base_Column_List" >
    id, serial_num, device_name, area, status,province
  </sql>
 
 <select id="selectByKeyword" resultMap="BaseResultMap">
  select id,serial_num,device_name,area,status,province from device where serial_num like CONCAT('%',#{keyword},'%' ) or 
  device_name like CONCAT('%',#{keyword},'%' ) or area like CONCAT('%',#{keyword},'%' )
  </select>
  
  <select id="selectByProvinceId" resultMap="BaseResultMap" >
  select id,serial_num,device_name,area,status,province from device where province=#{province,jdbcType=INTEGER}
  </select>
 
 <select id="selectAllDevice" resultMap="BaseResultMap">
 select id,serial_num,device_name,area,status,province from device
 </select>
 
 <select id="selectDeviceOnLine" resultMap="BaseResultMap">
  select id,serial_num,device_name,area,status,province from device where status=1
 </select>
 
  <select id="selectDeviceBySerialNum" resultMap="BaseResultMap" parameterType="java.lang.String">
  select id,serial_num,device_name,area,status,province from device where serial_num=#{serialNum,jdbcType=VARCHAR}
 </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from device
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from device
    where id = #{id,jdbcType=INTEGER}
  </delete>
   
  <delete id="deleteBySerialNum" parameterType="java.lang.String">
    delete from device where  serial_num = #{serialNum,jdbcType=VARCHAR}
  </delete>

  <insert id="insert" parameterType="com.timmy.entity.Device" >
    insert into device (id, serial_num, device_name, 
      area, status,province)
    values (#{id,jdbcType=INTEGER}, #{serialNum,jdbcType=VARCHAR}, #{deviceName,jdbcType=VARCHAR}, 
      #{area,jdbcType=VARCHAR}, #{status,jdbcType=INTEGER},#{province,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.timmy.entity.Device" >
    insert into device
    <trim prefix="(" suffix=")" suffixOverrides="," >
       <if test="id != null" >
        id,
      </if>
      
      <if test="serialNum != null" >
        serial_num,
      </if>
      <if test="deviceName != null" >
        device_name,
      </if>
      <if test="area != null" >
        area,
      </if>
      <if test="status != null" >
        status,
      </if>
       <if test="province != null" >
        province,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="serialNum != null" >
        #{serialNum,jdbcType=VARCHAR},
      </if>
      <if test="deviceName != null" >
        #{deviceName,jdbcType=VARCHAR},
      </if>
      <if test="area != null" >
        #{area,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        #{status,jdbcType=INTEGER},
      </if>
       <if test="province != null" >
        #{province,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
 
  <update id="updateByPrimaryKeySelective" parameterType="com.timmy.entity.Device" >
    update device
    <set >
      <if test="serialNum != null" >
        serial_num = #{serialNum,jdbcType=VARCHAR},
      </if>
      <if test="deviceName != null" >
        device_name = #{deviceName,jdbcType=VARCHAR},
      </if>
      <if test="area != null" >
        area = #{area,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        status = #{status,jdbcType=INTEGER},
      </if>
       <if test="province != null" >
        province = #{province,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.timmy.entity.Device" >
    update device
    set serial_num = #{serialNum,jdbcType=VARCHAR},
      device_name = #{deviceName,jdbcType=VARCHAR},
      area = #{area,jdbcType=VARCHAR},
      status = #{status,jdbcType=INTEGER},
      province = #{province,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
  
  <update id="updateStatusByPrimarykey" parameterType="com.timmy.entity.Device">
  update device set status = #{status,jdbcType=INTEGER} 
  where id = #{id,jdbcType=INTEGER} 
  </update>
</mapper>

需要注意的只有下面的這一部分,這回事關鍵詞查詢的語句 

實體類和mapper映射都可以使用mybaties-generator逆向生成工具進行生成

mybatis-generator-core-1.3.2.zip解壓放在本地文件夾中

下載地址:https://download.csdn.net/download/moshubai/11941711

然後修改

這個文件裏面數據庫的配置,如下

修改成自己的,然後在命令行進入 

這個文件所在目錄。輸入java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite,回車,就會在 src文件中生成mapper和實體類了

3.接下來是controller部分,這部分是接收前端請求,並且調用後端的接口的。

package com.timmy.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.timmy.entity.AttandenceRecords;
import com.timmy.entity.Device;
import com.timmy.entity.DeviceTemp;
import com.timmy.entity.Msg;
import com.timmy.entity.Person;
import com.timmy.entity.Province;
import com.timmy.service.DeviceService;
import com.timmy.service.ProvinceService;


@Controller
@RequestMapping("device")
public class DeviceController {

	@Autowired
	DeviceService deviceService;
	
	@Autowired
	ProvinceService provinceService;
	@RequestMapping("/queryDeviceList")
	public String queryDevice(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model) {
	
		PageHelper.startPage(pn, 15);
		List<Device>list=deviceService.selectAllDevice();
		PageInfo<Device>pageInfo=new PageInfo<Device>(list,10);
		model.addAttribute("pageInfo", pageInfo);
		return "deviceList";		
	}
	
	@RequestMapping("/queryDevices")
	public String queryDevice() {

		return "deviceList2";		
	}

	/*刷新設備列表*/
	@RequestMapping(value="/deviceList")
	@ResponseBody
	public Msg refreshDevice(@RequestParam(value="pn",defaultValue="1") Integer pn) {
		PageHelper.startPage(pn, 15);
		List<Device>list=deviceService.selectAllDevice();
		
		PageInfo page= new PageInfo(list,5);
		
		return Msg.success().add("pageInfo", page);
		
	}
	
	@RequestMapping(value="/selectDeviceById")
	@ResponseBody
	public Msg selectDeviceById(@RequestParam("id") int id) {
		Device device=deviceService.selectByPrimaryKey(id);
		
		return Msg.success().add("device", device);
		
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/deviceSn", method = RequestMethod.GET)
	public Msg getDevice() {
		List<Device> devices = deviceService.selectDeviceOnLine();
		System.out.println("設別信息" + devices);
		return Msg.success().add("device", devices);
	}
	
	@ResponseBody
	@RequestMapping(value = "/provinceList", method = RequestMethod.GET)
	public Msg getProvince() {
		//List<Device> devices = deviceService.selectDeviceOnLine();
		List<Province>province=provinceService.selectAllProvince();
		System.out.println("設別信息" + province);
		return Msg.success().add("device", province);
	}
	
	@RequestMapping(value = "/addDevice", method = RequestMethod.POST)
	public Msg saveDevice(@ModelAttribute DeviceTemp deviceTemp) {
		System.out.println("設備數據"+deviceTemp);
		Device device=new Device();
		device.setSerialNum(deviceTemp.getSerialNum());
		device.setDeviceName(deviceTemp.getDeviceName());
		device.setProvince(deviceTemp.getProvince());
		device.setArea(deviceTemp.getArea());
		device.setStatus(0);
		if(deviceService.selectDeviceBySerialNum(device.getSerialNum())==null){
			deviceService.insert(device);	
		}else{
			return Msg.fail();
		}
		//deviceService.insert(device);
		return Msg.success();
	}
	
	
	@RequestMapping(value = "/updateDevice", method = RequestMethod.POST)
	public Msg updateDevice(@ModelAttribute DeviceTemp deviceTemp) {
		System.out.println("設備數據"+deviceTemp);
		Device device=deviceService.selectByPrimaryKey(deviceTemp.getId());
		device.setSerialNum(deviceTemp.getSerialNum());
		device.setDeviceName(deviceTemp.getDeviceName());
		device.setProvince(deviceTemp.getProvince());
		device.setArea(deviceTemp.getArea());
		device.setStatus(0);
		try {
			deviceService.updateByPrimaryKey(device);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return Msg.fail();
		}
		return Msg.success();
	}
	
	@RequestMapping(value = "/searchKeyword", method = RequestMethod.GET)
	public String searchByKeyword(@RequestParam(value="pn",defaultValue="1")Integer pn,@RequestParam(value="province",defaultValue="0")int province,@Param("keyword")String keyword,Model model) {
		
		System.out.println("shen"+province);
		PageHelper.startPage(pn, 15);
		List<Device>list=new ArrayList<Device>();
		
		if(province!=0){
			list=deviceService.selectByProvinceId(province);
			System.out.println("通過編號查詢"+list);
		}else{
			list=deviceService.selectByKeyword(keyword);
		}
		PageInfo<Device>pageInfo=new PageInfo<Device>(list,10);
		model.addAttribute("pageInfo", pageInfo);
		return "deviceList";		
		
	}
	
	
	@RequestMapping(value = "/searchByProvince", method = RequestMethod.GET)
	public String searchByProvince(@RequestParam(value="pn",defaultValue="1")Integer pn,@Param("province")int province) {
		PageHelper.startPage(pn, 8);
		List<Device>list=deviceService.selectByProvinceId(province);
		
		PageInfo page= new PageInfo(list,5);
		 
		
		return "hello1";
	}
	
	@RequestMapping("/deleteDevice")
	public String deleteDevice(@RequestParam("id")int id) {
		deviceService.deleteByPrimaryKey(id);
		return "deviceList2";
		
	}
}

4.前端代碼

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
<base href="<%=basePath%>">
<title>Dynamic Face Device Auto Data Manage System</title>

<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css" />
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript"
	src="js/bootstrap-datetimepicker.zh-CN.js"></script>


</head>

<body>
	<nav class="navbar navbar-inverse" role="navigation">
		<div class="container-fluid">
			<div class="navbar-header">
				<a class="navbar-brand" href="#" style="height: 92px;"> </a>
			</div>
			<div class="collapse navbar-collapse" id="example-navbar-collapse">
				<ul class="nav navbar-nav navbar" style="margin: 1% 0 1% 34%;">
					<li class="active"><a class="icon-bar" href="#"
						style="background-color: #087b71"> <font
							style="font-size: 31px; font-weight: bold; font-style: italic;">Welcome
								to Fingerprint Attendance Device ADMS</font></a></li>
				</ul>
				<ul class="nav navbar-nav navbar-right" style="margin: 1% 0 1% 0%;">

				</ul>
			</div>
		</div>
	</nav>

	<div class="container-fluid">
		<div class="row">
			<div class="col-sm-2">
				<a href="#" class="list-group-item active"><span
					class="glyphicon glyphicon-home"></span>&nbsp;&nbsp;Menu </a> <a
					href="${pageContext.request.contextPath}/log/queryLogs"
					class="list-group-item"> <span
					class="glyphicon glyphicon-search" aria-hidden="true"> </span>&nbsp;Attendance
					Log
				</a> <a href="${pageContext.request.contextPath}/device/queryDevices"
					class="list-group-item"> <span class="glyphicon glyphicon-user"
					aria-hidden="true"> </span>&nbsp;Device Management
				</a>

			</div>
			<!--左邊菜單欄-->
			<div class="col-sm-10">
				<ol class="breadcrumb">
					<li class="active">Menu</li>
					<li class="active">Device Info</li>
				</ol>
				<div class="panel panel-default">
					<div class="panel-heading">Operation</div>
					<div class="panel-body">
						<form role="form" class="form-inline" action="${pageContext.request.contextPath }/device/searchKeyword">
							<div class="form-group">
								<label for="name">SerialNum</label> <input type="text"
									class="form-control" name="keyword" id="keywordSearch" placeholder="Input SerialNum/Area/Name">
							</div>
							&nbsp;&nbsp;&nbsp;&nbsp;
							
							
							<div class="form-group">
								<label>Province</label>								
								<select id="provinceSelect" class="form-control" name="province">
									
									
								</select>
							</div>
							<div class="form-group">
								<button type="submit" id="search_btn" class="btn btn-default">Start Search</button>
							</div>
						</form>



						<div class="row">
							<div class="col-md-6 col-md-offset-10">
								<button class="btn btn-primary" id="addDevice_btn">Add Device</button>
							</div>
						</div>

					</div>
				</div>
				<!-- 列表展示 -->
				<div class="table-responsive">
					
						<table class="table table-hover table-striped" id="emps_table">
							<thead>
								<tr>
									<th>ID</th>
									<th>DeviceSn</th>
									<th>Name</th>
									<th>Parameter</th>
									<th>Province</th>
									<th>Status</th>
									<th colspan="3">Operation</th>
								</tr>
							</thead>
							<tbody>

							</tbody>
						</table>
					
				</div>
			</div>
		</div>
		<!-- 分頁 -->
		<div class="row">
			<!-- 顯示分頁文字信息 -->
			<div class="col-md-6" id="page_info_area"></div>
			<!-- 顯示分頁條信息 -->
			<div class="col-md-4 col-md-offset-2" id="page_nav_area"></div>
		</div>
	</div>
	<!-- 添加設備的模態框-->
	<div class="modal fade" id="deviceModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<!-- 模態框的標題 -->
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">Add Device</h4>
				</div>
				<!-- 模態框的主體-表單頭部 -->
				<form class="form-horizontal" id="form4">
					<div class="modal-body">
						<div class="form-group  form-group-lg">
							<label class="control-label col-xs-3">SerialNum</label>
							<div class="col-sm-5">
								<input class="form-control input-lg" name="serialNum" >
							</div>
						</div>
                        
                        <div class="form-group  form-group-lg">
							<label class="control-label col-xs-3">Name</label>
							<div class="col-sm-5">
								<input class="form-control input-lg" name="deviceName">
							</div>
						</div>
                         
						<div class="form-group  form-group-lg">
							<label class="control-label col-xs-3">Parameter</label>
							<div class="col-sm-5">
								<input class="form-control input-lg" name="area">
							</div>
						</div>
                        
                        <div class="form-group  form-group-lg">
							<label class="control-label col-xs-3">Parameter</label>
							<div class="col-sm-5">
								<select id="provinceSelector" class="form-control" name="province">		
								</select>
							</div>
						</div>
                           
					</div>
					<!-- 模態框的尾部 -->
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
						<button type="submit" class="btn btn-primary" id="deviceSave">Save</button>
					</div>
				</form>
			</div>
		</div>
	</div>


    <!-- 修改設備的模態框-->
	<div class="modal fade" id="deviceUpdateModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<!-- 模態框的標題 -->
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">Update Device</h4>
				</div>
				<!-- 模態框的主體-表單頭部 -->
				<form class="form-horizontal" id="form5">
					<div class="modal-body">
					     <input type="hidden" name="id"  />
						<div class="form-group  form-group-lg">
							<label class="control-label col-xs-3">SerialNum</label>
							<div class="col-sm-5">
								<input class="form-control input-lg" name="serialNum" >
							</div>
						</div>
                        
                        <div class="form-group  form-group-lg">
							<label class="control-label col-xs-3">Name</label>
							<div class="col-sm-5">
								<input class="form-control input-lg" name="deviceName">
							</div>
						</div>
                         
						<div class="form-group  form-group-lg">
							<label class="control-label col-xs-3">Parameter</label>
							<div class="col-sm-5">
								<input class="form-control input-lg" name="area">
							</div>
						</div>
                        
                        <div class="form-group  form-group-lg">
							<label class="control-label col-xs-3">Parameter</label>
							<div class="col-sm-5">
								<select id="provinceUpdateSelector" class="form-control" name="province">		
								</select>
							</div>
						</div>
                           
					</div>
					<!-- 模態框的尾部 -->
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
						<button type="submit" class="btn btn-primary" id="deviceUpdate">Save</button>
					</div>
				</form>
			</div>
		</div>
	</div>


	<!-- 選擇設備號-->
	<div class="modal fade" id="setFkNameModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title">setFKName</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" id="form1">
						<div class="form-group">
							<label class="control-label col-xs-3">Device Name</label>
							<div class="col-xs-9">
								<input class="form-control" name="name" id="fkName">
							</div>
						</div>
						<div class="form-group">
							<label class="control-label col-xs-3">DeviceId</label>
							<div class="col-xs-9">
								<select class="form-control" name="deviceSn" id="fkDeviceSn">
								</select>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">return</button>
					<button type="button" class="btn btn-primary"
						id="FkNameSave_button">save</button>
				</div>
			</div>
		</div>
	</div>




	<script type="text/javascript">
	<!-- 添加模態框(Modal)插件 -->
	   var totalRecord,currentPage;
		$(function() {
            
			
			 to_page(1);
			 setInterval("to_page(1)", 20000); 
			$(".form_datetime").datetimepicker({
				format : "yyyy-mm-dd hh:ii",
				autoclose : true,
				todayBtn : true,
				todayHighlight : true,
				showMeridian : true,
				pickerPosition : "bottom-left",
				language : 'zh-CN',//中文,需要引用zh-CN.js包
				startView : 2,//月視圖
				minView : 2
			//日期時間選擇器所能夠提供的最精確的時間選擇視圖
			});
			 getProvince("#provinceSelect");  
		});
		
		
		function to_page(pn){
			$.ajax({
				url:"${pageContext.request.contextPath}/device/deviceList",
				data:"pn="+pn,
				type:"GET",
				success:function(result){
					//console.log(result);
					// 1. 解析並顯示員工數據
					build_emp_table(result);
					// 2. 解析並顯示分類信息
					buid_page_info(result);
					// 3. 解析並顯示分頁條信息
					build_page_nav(result);
				}
			});
		}
		
		
		
		
		//解析顯示設備信息
		function build_emp_table(result){
			$("#emps_table tbody").empty();
			var emps = result.extend.pageInfo.list;
			var i = result.extend.pageInfo.startRow;
			$.each(emps,function(index,item){
				//alert(item.empName);
			    var statusTd="";
				var idTd = $("<td></td>").append(item.id);
				var deviceSnTd = $("<td></td>").append(item.serialNum);
				var nameTd = $("<td></td>").append(item.deviceName);
			 	var parameterTd = $("<td></td>").append(item.area); 
		        
				var provinceTd = $("<td></td>").append(item.province);
				
				if(item.status==0){
					statusTd = $("<td></td>").append("<lable class=\"label label-danger\">Offline</lable>");
				}else{
					statusTd = $("<td></td>").append("<lable class=\"label label-success\">Online</lable>");
				}
				
				var updateBtu = $("<button></button>").addClass("btn btn-info btn-sm update_btu")
				.append("<span></span>").append("Update");
	           //爲編輯按鈕添加一個自定義的屬性,來表示當前的員工id
	            updateBtu.attr("update-id",item.id);
				
				var delBtu = $("<button></button>").addClass("btn btn-danger btn-sm delete_btu")
							.append("<span></span>").append("delete");
				//爲刪除按鈕添加一個自定義的屬性,來表示當前的員工id
				delBtu.attr("delete-id",item.id);
				var btuTd = $("<td></td>").append(delBtu).append(" ").append(updateBtu);
				//append方法執行完後仍返回原來的元素
				$("<tr></tr>").append(idTd)
					.append(deviceSnTd)
					.append(nameTd)
					.append(parameterTd)
					.append(provinceTd)
					.append(statusTd)
					.append(btuTd)
					.appendTo("#emps_table tbody");
			})
		}
		//解析顯示分頁信息
		function buid_page_info(result){
			$("#page_info_area").empty();
			var pageH=$("<h4 style=\"margin: 0 0 0 38%;\"></h4>").append("Current Page:"+result.extend.pageInfo.pageNum +
					", Count Page:"+result.extend.pageInfo.pages +
					", All Records:"+result.extend.pageInfo.total);
			$("#page_info_area").append(pageH);
			totalRecord = result.extend.pageInfo.pages;
			currentPage = result.extend.pageInfo.pageNum;
		}
		
		//解析顯示分頁條信息
		function build_page_nav(result){
			$("#page_nav_area").empty();
			var ul = $("<ul></ul>").addClass("pagination");
			
			var firstPageLi = $("<li></li>").append($("<a></a>").append("FirstPage"));
			var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
			if(result.extend.pageInfo.hasPreviousPage == false){
				prePageLi.addClass("disabled");
			}else{
				//添加單擊事件
				prePageLi.click(function(){
					to_page(result.extend.pageInfo.pageNum -1);
				});
				firstPageLi.click(function(){
					to_page(1);
				});
			}
			var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
			var lastPageLi = $("<li></li>").append($("<a></a>").append("LastPage"));
			if(result.extend.pageInfo.hasNextPage == false){
				nextPageLi.addClass("disabled");
			}else{
				//添加單擊事件
				nextPageLi.click(function(){
					to_page(result.extend.pageInfo.pageNum +1);
				});
				lastPageLi.click(function(){
					to_page(result.extend.pageInfo.pages );
				});
			}
			//添加首頁和前一頁
			ul.append(firstPageLi).append(prePageLi);
			$.each(result.extend.pageInfo.navigatepageNums,function(index,item){
				var numLi = $("<li></li>").append($("<a></a>").append(item));
				//添加每一個遍歷出來的頁碼
				if(item == result.extend.pageInfo.pageNum){
					numLi.addClass("active");
				}
				numLi.click(function(){
					to_page(item);
				});
				ul.append(numLi);
			});
			//添加最後一頁和末頁
			ul.append(nextPageLi).append(lastPageLi);
			//把 ul 添加到 navElv 中去
			var navElv = $("<nav></nav>").append(ul);
			
			navElv.appendTo("#page_nav_area");
		} 
		
		
		//彈出添加機器
		$("#addDevice_btn").click(function() {
			//初始化模態框
			//也可以這麼做

		 	$("#deviceModal").modal({
				backdrop : "static"
			}); 
		//	to_searchByKeyword(1);
		 	getProvince("#provinceSelector"); 
		});

		
		
		
		
		
		//新增設備
		$("#deviceSave")
				.click(
						function() {
							$
									.ajax({
										url : "${pageContext.request.contextPath}/device/addDevice",
										type : "POST",
										data:$("#form4").serialize(),
										success : function(result) {
											if(result.code == 100){ 
												//alert(result.msg);
												//員工保存成功
												//1.關閉模態框
												$("#deviceModal").modal('hide');
												//2.跳轉到最後一頁
												alert(result.msg);
												//回到當前頁
												to_page(currentPage);
											 }else{
												 alert("SerialNum exist!");
											} 
										}
									});
						});

		//修改設備
		$("#deviceUpdate")
				.click(
						function() {
							$
									.ajax({
										url : "${pageContext.request.contextPath}/device/updateDevice",
										type : "POST",
										data:$("#form5").serialize(),
										success : function(result) {
											if(result.code == 100){ 
												//alert(result.msg);
												//員工保存成功
												//1.關閉模態框
												$("#deviceModal").modal('hide');
												//2.跳轉到最後一頁
												alert(result.msg);
												//回到當前頁
												to_page(currentPage);
											 }else{
												 alert("Parameter error!");
											} 
										}
									});
						});

		function getDevice(ele) {
			//alert("shebei")
			$(ele).empty();
			$.ajax({
				url : "${pageContext.request.contextPath}/device/deviceSn",
				type : "GET",
				success : function(result) {
					$.each(result.extend.device, function() {
						var optionEle = $("<option></option>").append(this.sn)
								.attr("value", this.sn);
						optionEle.appendTo(ele);
					})

				}

			});
		}
		
		function getProvince(ele) {
			//alert("shebei")
			$(ele).empty();
			$.ajax({
				url : "${pageContext.request.contextPath}/device/provinceList",
				type : "GET",
				success : function(result) {
					var option11 = $("<option></option>").append("enter area")
					.attr("value", "0");
					option11.appendTo(ele);
					$.each(result.extend.device, function() {
						var optionEle = $("<option></option>").append(this.province)
								.attr("value", this.id);
						optionEle.appendTo(ele);
					})

				}

			});
		}

		//爲刪除按鈕綁定單擊事件
		$(document).on("click",".delete_btu",function(){
					
			var empId = $(this).parents("tr").find("td:eq(1)").text();
			//alert(empName);
			if(confirm("Do you want to delete【"+empId +"】device?")){
				//確認,發送ajax請求,刪除
				$.ajax({
					url:"${pageContext.request.contextPath}/device/deleteDevice?id="+$(this).attr("delete-id"),
					type:"GET",
					success:function(result){
						alert(result.msg);
						//回到當前頁
						to_page(currentPage);
					}
				});
			}
		});
		
		//爲刪除按鈕綁定單擊事件
		$(document).on("click",".update_btu",function(){
		//	alert("修改主鍵"+$(this).attr("update-id"));
			getProvince("#provinceUpdateSelector");
			getDeviceList($(this).attr("update-id"));
			$("#deviceUpdate").attr("update-id",$(this).attr("update-id"));
			$("#deviceUpdateModal").modal({
				backdrop : "static"
			}); 
			
		});
		
		//獲取員工信息
		function getDeviceList(id){
			$.ajax({
				url:"${pageContext.request.contextPath}/device/selectDeviceById?id="+id,
				type:"GET",
				success:function(result){
					//console.log(result);
					var deviceData = result.extend.device;
					$("#deviceUpdateModal input[name=id]").val([deviceData.id]);
					$("#deviceUpdateModal input[name=serialNum]").val([deviceData.serialNum]);
					$("#deviceUpdateModal input[name=deviceName]").val([deviceData.deviceName]);
					$("#deviceUpdateModal input[name=area]").val([deviceData.area]);
					$("#deviceUpdateModal select").val([deviceData.province]);
				}
			});
			
		}
		
		
		//完成全選/全不選功能
		$("#check_all").click(function() {
			//prop修改和讀取原生dom屬性的值
			//attr獲取自定義屬性的值
			$(".check_item").prop("checked", $(this).prop("checked"));
		});

		//單個的選擇框全選,頂上的也選擇
		$(document)
				.on(
						"click",
						".check_item",
						function() {
							//判斷當前選中的元素是否是全部的元素
							var flag = ($(".check_item:checked").length == $(".check_item").length)
							$("#check_all").prop("checked", flag);

						});
	</script>
	<!-- 底部頁腳部分 -->
	<div class="footer">
		<p class="text-center">2019 &copy; Timmy.</p>
	</div>

</body>
</html>

 後續,我會把項目上傳,介紹一些剛入門的不太熟悉的功能怎麼用

附上項目源碼連接https://download.csdn.net/download/moshubai/11945282

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章