【发布时间】:2022-06-10 20:47:35
【问题描述】:
我想在页面刷新后保留多个复选框的值。根据我的研究,我发现了两个可行的选项:1)使用会话变量或 2)通过 localStorage。我决定选择 localStorage,因为它针对现代浏览器进行了优化。我根据这个例子编写了代码:Keep checkbox checked even after page refresh?。 当我打开/关闭开关时,它可以正常工作。但是,如果我打开它并刷新页面(进入地址栏并按回车键),它会被取消选中,并且数据库中的值设置为 0(从 1 开始)。
我不知道代码有什么问题。有人可以给我建议吗?
谢谢
<?php
$servername = "localhost";
$username = "xxxxx";
$password = "xxxxx";
$database ="xxxxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<?php
if(isset($_POST) && count($_POST) >= 0){
if (isset($_POST['checkbox1'])) {
$query1 = "UPDATE switch_status SET status = 1 WHERE switch_id = 1";
} else {
$query1 = "UPDATE switch_status SET status = 0 WHERE switch_id = 1";
}
$result1 = mysqli_query($conn, $query1) or die(mysqli_error());
}
?>
<form id="form" action="" method="POST" >
<label>
Checkbox 1
<input type="checkbox" id = "check" name="checkbox1" value="1" autocomplete="off" onchange="document.getElementById('form').submit();"
<?php if(isset($_POST['checkbox1'])) { echo 'checked="checked"'; } ?>>
</label>
</form>
<script>
$('#check').on('click', function(){
if(localStorage.getItem("checkedbox") == 'true') {
$(this).prop(checked, 'false');
localStorage.setItem("checkedbox", 'false');
}
else {
$(this).prop(checked, 'true');
localStorage.setItem("checkedbox", 'true');
}
})
</script>
</body>
</html>
【问题讨论】: