前端学习笔记(2406261):jquery使用checkbox控制页面自动刷新

发布于:2024-06-27 ⋅ 阅读:(180) ⋅ 点赞:(0)

需求

这是一个物联网的演示项目,web端能够实时显示后台数据的变化,其流程非常简单:

  1. 用户登录
  2. 登录成功后显示主界面面
  3. 主界面进入后自动显示数据
  4. 数据两秒钟自动刷新一次
  5. 设置日期和时间可以对数据进行筛选
  6. 勾选掉自动刷新后,停止自动刷新
  7. 点击刷新按钮可以强制刷新。

登录页面

登录页面可以输入用户名和密码,提交到服务端验证后,可以跳转到主界面。
登录界面

主页面

主界面的元素有:开始时间,结束时间,自动刷新开关,刷新按钮
表格的列有:序号、温度、压力、电压、位置、行程开关状态、数据上报的时间等。

说明数据均为模拟数据,而非实际数据。

主界面

API

系统一共有两个API,分别是:

  • login:用于用户登录
  • 获取数据:获取设备数据

用户登录login

login方法采用post,发送用户名和密码,如果登录成功,返回的code0,且附带一个token,后续请求需要将token放在header中。
login方法

获取数据getdata

登录成功后,使用getdata来获取数据,采用post请求,需要将token放在header中。body为json格式,可以传递fromto两个参数,其格式为yyyy-mm-dd hh:nn:ss,这两个参数不是必须的。
请求成功后,将返回数据包,包括codemsgdata,其中data是一个数组,包含了传感器的数据,分别是:temperaturepressurevoltagepositionswitchtime
getdata方法

代码

登录页面

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
    <style>
        body {
            background-color: #333;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        form {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        input {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <form id="loginForm" method="post">
        <input type="text" id="username" placeholder="用户名" required>
        <input type="password" id="password" placeholder="密码" required>
        <button type="submit">登录</button>
    </form>
    <script>
        document.getElementById('loginForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            if (!username || !password) {
                alert('用户名和密码不能为空');
                return;
            }
            const data = {
                username: username,
                password: password
            };
            fetch('/mgr/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 0) {
                    document.cookie = 'token=' + result.token;
                    window.location.href = '/main';
                } else {
                    alert('登录失败,请检查用户名和密码');
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });
    </script>
</body>
</html>

主页面

页面使用了jquery,用checkbox来控制页面的刷新,主要的代码是:

$("#autoRefresh").click(function(){
	if ($("#autoRefresh").is(':checked')){
		interval_id = window.setInterval(queryData, 2000);
	}else{
		window.clearInterval(interval_id)
	}
})

可以使用is方法来判断checked来确定checkbox是否处于选中状态。

另外,通过window.setInterval的方法,可以设置一个定时器,实现数据的定时获取。

完整的代码如下:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据查询</title>
    <style>
        body {
            background-color: #333;
            color: #fff;
        }
		.centered {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
		}
		
		table {
			border-collapse: collapse;
			width: 80%;
			margin: 0 auto;
			margin-top: 40px;
		}
		th, td {
			border: 1px solid #ccc;
			padding: 8px;
			text-align: center;
		}
		th {
			background-color: #333;
		}
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>
<body>
    <div class="centered">
        <label for="startTime">开始时间:</label>&nbsp
        <input type="datetime-local" id="startTime">&nbsp &nbsp
        <label for="endTime">结束时间:</label>&nbsp
        <input type="datetime-local" id="endTime">&nbsp &nbsp
		<input type="checkbox" id="autoRefresh" checked>自动刷新(2s)</input>&nbsp  &nbsp
		<button id="queryBtn">立即刷新</button>
    </div>
    <table id="resultTable">
        <thead>
            <tr>
                <th>序号</th>
                <th>温度</th>
                <th>压力</th>
                <th>电压</th>
                <th>位置</th>
                <th>开关</th>
                <th>时间</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
     <script>
        $(document).ready(function() {
            var token = getCookie("token");
            if (!token) {
                window.location.href = "/login";
            }
            $("#queryBtn").click(queryData);
			//使用定时器刷新
			var interval_id = setInterval(queryData, 2000);
			$("#autoRefresh").click(function(){
				if ($("#autoRefresh").is(':checked')){
					interval_id = window.setInterval(queryData, 2000);
				}else{
					window.clearInterval(interval_id)
				}
			})

			//初始化时刷新
			queryData();
        });

        function getCookie(name) {
            var value = "; " + document.cookie;
            var parts = value.split("; " + name + "=");
            if (parts.length == 2) return parts.pop().split(";").shift();
        }
		function queryData(){
			var startTime = $("#startTime").val();
			if (startTime && startTime.length>6){
				startTime = moment(startTime).format("YYYY-MM-DD HH:mm:ss");
			}
			var endTime = $("#endTime").val();
			if (endTime && endTime.length>6){
				endTime = moment(endTime).format("YYYY-MM-DD HH:mm:ss");
			}
			var data = {
				'from': startTime,
				'to': endTime
			};
			var token = getCookie("token");
			$.ajax({
				url: "/mgr/getdata",
				type: "POST",
				contentType: "application/json",
				data: JSON.stringify(data),
				headers: {
					"token": token
				},
				success: function(response) {
					if (response.code === 0) {
						displayData(response.data);
					} else if (response.code === 340) {
						window.location.href = "/login";
					} else {
						alert(response.msg);
					}
				},
				error: function() {
					alert("请求失败,请稍后重试");
				}
			});
		}
        function displayData(data) {
            var tableBody = $("#resultTable tbody");
            tableBody.empty();
            data.forEach(function(item, index) {
                var row = $("<tr></tr>");
                row.append($("<td></td>").text(index + 1));
                row.append($("<td></td>").text(item.temperature));
                row.append($("<td></td>").text(item.pressure));
                row.append($("<td></td>").text(item.voltage));
                row.append($("<td></td>").text(item.position));
                row.append($("<td></td>").text(item.switch ? "开" : "关"));
                row.append($("<td></td>").text(item.time));
                tableBody.append(row);
            });
        }
    </script>
</body>
</html>

关于后端

回头再写吧,估计也没人看,有需要的可以留言。


网站公告

今日签到

点亮在社区的每一天
去签到