【问题标题】:Refresh a PHP page after checking/unchecking a checkbox选中/取消选中复选框后刷新 PHP 页面
【发布时间】:2021-05-17 02:40:35
【问题描述】:

我对 PHP 很陌生,所以请帮忙。 我需要一个带有复选框的 php 网页。每次我对复选框执行操作时,该页面都会自行刷新(因此无论是选中还是取消选中)。刷新后,页面应保留复选框的最新值。 我尝试使用以下示例修改我从 StackOverflow 获取的另一个代码,但它没有按我希望的那样工作。 有什么建议吗?

<?php
session_start();
$checked = "";


if($_SESSION['myaction'] != $_SESSION['value'])
{
    if(isset($_POST['sharks']))
    {
        $_SESSION['value'] = $_POST['sharks'];
    }
    else
    {
        $_SESSION['value'] = '';
        echo ":(";
    }
    $_SESSION['myaction'] = $_SESSION['value'];
}
?>

<form action="" method="POST">

<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
    echo "checked='checked'";
}
$myaction = 2;
print ">";
?>

</form>

【问题讨论】:

  • 与页面的任何交互(即:复选框)都应使用 javascript 处理
  • 我的意图是仅将 javascript 用于图形目的,我希望 php 来管理整个流程。我举的例子确实只是在 php 中,但它用一个按钮刷新页面。我需要类似的东西,但没有按钮,只有一个复选框。
  • a checkbox 没有提交表单或刷新页面的固有方法

标签: php checkbox page-refresh


【解决方案1】:
<form method='POST'>
    <input name='sharks' type='checkbox' value='1' id='sharks' />
</form>

一些使用localStorage(或sessionStorage)的简单、普通的Javascript。 click 处理程序将设置检查状态,并且在页面加载时,该值将有助于re-check,或不帮助复选框。 Javascript 就是为了这种目的而设计的——尽管当页面重新加载时完全可以使用 PHP 重新检查复选框,只要它有某种方法来检查值与存储值或表单提交。

document.addEventListener('DOMContentLoaded',()=>{
    let chk=document.querySelector('input[type="checkbox"][name="sharks"]');
        chk.checked=localStorage.getItem( chk.name )==null || localStorage.getItem( chk.name )=='false' ? false : true;
        
        chk.addEventListener('click',e=>{
            localStorage.setItem( chk.name, chk.checked )
            location.reload();
        });
});

【讨论】:

    【解决方案2】:

    如果您不想要复选框的行为,请不要使用复选框。

    如果您要提交数据,请使用提交按钮。用户希望提交按钮触发页面重新加载。

    <?php
        $current_state = get_state_from_database_or_session_or_whatever();
        if (isset($_POST['new_state'])) {
            if ($_POST['new_state']) == "on") {
                 $current_state = "off";
            } else {
                 $current_state = "on";
            }
            update_datebase_or_session_or_whatever_with_new_state($current_state);
        }
        $other_state = "off";
        if ($current_state == "off") {
            $other_state = "on";
        }
    ?>
    <p>The current state is <?php echo $current_state; ?></p>
    <form method="post">
        <button name="state" value="<?php echo $other_state; ?>">Set state to <?php echo $other_state; ?></button>
    </form>
        
    

    【讨论】:

      【解决方案3】:

      您需要做的非常简单——假设您在同一页面上提交表单。

      <?php
       $filterUsers=array();
       
       if(isset($_GET['users'])){
          foreach($_GET['users'] as $key){
               $filterUsers[]=$key;
       }
      
       function valueInFilter($value){
          if(in_array($value, $filterUsers)){
              echo "checked";
            }else{
             echo "";
          }
       }
      
      
      ?>
       
       <html>
       <head>Filter </head>
       <body>
          <form method="get" action="<?php echo 
              htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> 
      
             <input type="checkbox" name="users[]" value="john" id="1" <?php 
                 valueInFilter("john",$filterUsers) ?>>
             <label for="1"> John doe</label><br>
             
            <input type="checkbox" name="users[]" value="john" id="2" <?php 
                 valueInFilter("mayor",$filterUsers) ?>>
             <label for="2"> John Mayor</label><br>
          </form>
       </body>
       </html>
      

      【讨论】:

        【解决方案4】:

        不是像 Abronsius 教授所写的 PHP 的工作。

        用 JavaScript 写成这样:

        (() => {
            // on page reloaded
        
            const checkboxNode = document.getElementById('sharks')
        
            if (localStorage.getItem('sharkCheckBox')) {
                // the checkbox is stored as CHECKED
                // e.g. check the checkbox again or what ever:
                checkboxNode.checked = true
            } else {
                // the checkbox is stored as NOT checked
            }
        
            // handle the click
            checkboxNode.addEventListener('click', function() {
                // get the checkbox status
                const isChecked = this.checked
                // store the checked status inside the browser cache
                localStorage.setItem('sharkCheckBox', isChecked)
                // there are several ways to to an page reload. Here an example
                // see details here https://stackoverflow.com/a/39571605/7993505
                location.reload()
            })
        })()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-24
          • 2014-04-03
          • 2013-08-17
          相关资源
          最近更新 更多