簡體   English   中英

頁面刷新后如何保留復選框值?

[英]How can I retain checkbox value after page refresh?

我想在頁面刷新后保留多個復選框的值。 根據我的研究,我發現了兩個可行的選項:1)使用會話變量或 2)通過 localStorage。 我決定選擇 localStorage,因為它針對現代瀏覽器進行了優化。 我根據這個例子編寫了代碼: 即使在頁面刷新后保持復選框被選中? . 當我打開/關閉開關時,它可以正常工作。 但是,如果我打開它並刷新頁面(進入地址欄並按回車鍵),它將被取消選中,並且數據庫中的值設置為 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 post 變量中設置 checked 屬性(如果您只是刷新頁面而不提交,它將不存在),而是利用 localStorage 數據。 您還可以稍微簡化您的功能

<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>

我認為$_POST超全局總是被定義的,所以你的檢查if(isset($_POST) && count($_POST) >= 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);
}

網頁沒有記憶。 當您從表單“提交”數據並再次訪問同一個網頁時,您擁有的唯一內容就是 $_REQUEST、$_POST 和/或 $_GET 中的內容。

可以將內容保存在 $_SESSION 中,但這可能不是您要問的。 警告:這在您只有一個 Web 服務器時才有效。 大型網站交替使用多個服務器; “會話”在這種情況下不起作用; 需要一個數據庫。

相反,您需要查看 $_GET (等)中的內容並使用它來構造您需要的值。 在“復選框”的情況下,您必須實際修改<input>以包含關鍵字“checked”。 “選項”和“文本”也是如此。 對於“文本”,您在適當轉義文本后填寫“值=”(使用htmlentities() )。

至於“本地存儲”與“會話”與“數據庫”——性能差異並不顯着。 如果該值在 $_POST (等)中,那么這是最省力的。

您可以簡單地使用 $_REQUEST 來避免知道它是<form method=POST>還是<form method=GET>

對於那些想知道的人,我通過使用會話變量而不是 localStorage 數據解決了我的問題。 這是通過遵循以下線程完成的: 將選中的復選框從表單中存儲在會話中,並保持選中的復選框狀態,除非 unchecked

感謝所有幫助過我的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM