【问题标题】:How can I retain checkbox value after page refresh?页面刷新后如何保留复选框值?
【发布时间】: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>  
 

【问题讨论】:

    标签: php jquery mysql


    【解决方案1】:

    使用 localStorage 数据,而不是从 PHP post 变量设置 checked 属性(如果您只是刷新页面而不提交,则不会存在)。您还可以稍微简化您的功能

    <form id="form" action="" method="POST">
      <label>Checkbox 1 <input type="checkbox"  id = "check" name="checkbox1" value="1" autocomplete="off" /> </label>
    </form>
    
    <script>
      // start by retrieving the current state
      $(document).ready(function() {
        let isChecked = localStorage.getItem("checkedbox");
        // now set it
        $('#check').prop('checked', isChecked)
      });
    
      $('#check').on('click', function() {
        localStorage.setItem("checkedbox", $(this).prop('checked'));
        // if you really want to submit the form when someone checks it...
        $('form').submit();
      })
    </script>
    

    【讨论】:

      【解决方案2】:

      网页没有内存。当您从表单“提交”数据并再次访问同一网页时,您所拥有的唯一内容就是 $_REQUEST、$_POST 和/或 $_GET 中的内容。

      您可以将内容保存在 $_SESSION 中,但这可能不是您要问的。警告:only 如果您只有一个 Web 服务器,则该方法有效。大型网站交替使用多个服务器; “会话”在这种情况下不起作用;需要一个数据库。

      相反,您需要查看 $_GET (etc) 中的内容并使用它来构造您需要的值。对于“复选框”,您必须实际修改&lt;input&gt; 以包含关键字“checked”。 “选项”和“文本”也是如此。对于“文本”,您在适当转义文本后填写“值 =”(使用 htmlentities())。

      至于“本地存储”与“会话”与“数据库”——性能差异并不显着。如果值在 $_POST (etc) 中,那么这是最省力的。

      您可以简单地使用 $_REQUEST 来避免知道它是 &lt;form method=POST&gt; 还是 &lt;form method=GET&gt;。

      【讨论】:

        【解决方案3】:

        对于那些想知道的人,我通过使用会话变量而不是 localStorage 数据解决了我的问题。这是通过以下线程完成的:Store a checked checkbox from a form in a session 和 keeping checked checkbox state unless unchecked。

        感谢所有帮助过我的人。

        【讨论】:

          【解决方案4】:

          我认为 $_POST 超全局总是被定义的,所以你的检查 if(isset($_POST) &amp;&amp; count($_POST) &gt;= 0){ 总是正确的。
          此外,当您有一个未选中的复选框时,它不会发布,因此您的 $_POST 对于有效请求将为空。在地址栏中按 Enter 会发出 GET 请求,但您的代码无法区分 GET 和 POST 请求,因此不要检查是否设置了 $_POST,而是检查请求方法。

          if ($_SERVER["REQUEST_METHOD"] == "POST") {
              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);
          }
          

          【讨论】:

            猜你喜欢
            • 2020-12-28
            • 2011-08-23
            • 1970-01-01
            • 2014-04-03
            • 2021-03-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多