如何在刷新时重新填充表单中的复选框并将表单值发布到页面


How to repopulate checkboxes in form on refresh AND post the form values to page?

当页面刷新或发送到另一个页面,然后再返回时,我使用ajax脚本重新填充页面上的复选框。脚本运行良好,因为页面刷新后仍将选中复选框。

我遇到的问题是这些复选框起到了过滤器的作用。因此,当点击它时,它会发布到页面上,我的php脚本会将每个值放入一个字符串中,用于查询。刷新页面时,复选框将保持选中状态,但不会将值发布到页面。在页面刷新时重新填充我选中的复选框后,我如何让这个Ajax脚本POST表单的值?

这是Ajax脚本:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script>
  function handleButtonClick(button){
    if ($(button).text().match("Check all")){
      $(":checkbox").prop("checked", true)
    } else {
      $(":checkbox").prop("checked", false)
    };
    updateButtonStatus();
  }
  function updateButtonStatus(){
    var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
    $("button").text(allChecked? "Uncheck all" : "Check all");
  }
  function updateCookie(){
    var elementValues = {};
    $(":checkbox").each(function(){
      elementValues[this.id] = this.checked;
    });
    elementValues["buttonText"] = $("button").text();
    $.cookie('elementValues', elementValues, { expires: 7, path: '/' })
  }
  function repopulateFormELements(){
    var elementValues = $.cookie('elementValues');
    if(elementValues){
      Object.keys(elementValues).forEach(function(element) {
        var checked = elementValues[element];
        $("#" + element).prop('checked', checked);
      });
      $("button").text(elementValues["buttonText"])
    }
  }
  $(":checkbox").on("change", function(){
    updateButtonStatus();
    updateCookie();
  });
  $("button").on("click", function() {
    handleButtonClick(this);
    updateCookie();
  });
  $.cookie.json = true;
  repopulateFormELements();

</script>

同一页面上的PHP将检查的内容放入字符串中,用于我的查询

if (isset($_POST["2kandunder"])) {
$arguments[] = "AND `2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "AND `2kto4k` = 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "AND 4kandup = 'yes'";
}
if(!empty($arguments)) {
$str = implode($arguments);
}

和html表单

 <form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" id="1" onchange="$('#form').submit();" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> $2000 And Under   
<input type="checkbox" name="2kto4k" class="checkbox" id="2" onchange="$('#form').submit();" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> $2001 To $4000
<input type="checkbox" name="4kandup"  class="checkbox" id="3" onchange="$('#form').submit();" <?=(isset($_POST['4kandup'])?' checked':'')?>/> $4001 And Up   

我已经尝试将以下内容添加到我的ajax中,但我对ajax完全陌生,这完全是猜测。此代码使页面开始闪烁,大约5秒钟后页面将转到"找不到页面"。

$('#form').submit(); 

当您存储cookie时,您也可以在PHP中使用它的信息来重新填充查询过滤器和表单上的复选框

<?php
    $checkboxes = array('checkbox1' => false, 'checkbox2' => false, 'checkbox3' => false, 'checkbox4' => false, );
    if (isset($_COOKIE['elementValues'])) {
        /* 
            Cookie values are stored like JSON
        */
        $raw = json_decode($_COOKIE['elementValues'], true); //cast to array
        var_dump($raw);
        foreach($raw as $input_name => $value) {
            if (isset($checkboxes[$input_name])) {
                $checkboxes[$input_name] = $value; //true/false
            }
        }
    }
    var_dump($checkboxes);

    if (isset($_POST["checkbox1"]) || $checkboxes['checkbox1']) {
        $arguments[] = "AND `2kandunder` = 'yes'";
    }
    if (isset($_POST["checkbox2"]) || $checkboxes['checkbox2']) {
        $arguments[] = "AND `2kto4k` = 'yes'";
    }
    if (isset($_POST["checkbox3"]) || $checkboxes['checkbox3']) {
        $arguments[] = "AND 4kandup = 'yes'";
    }
    $str = '';
    if(!empty($arguments)) {
        $str = implode(' ',$arguments);
    }
    echo 'QUERY FILTER : ' . $str;
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Checkbox state - Coookies</title>
    </head>
    <body>
        <form action="#" method="POST">
            <?php
                foreach($checkboxes as $input_name => $checked) {
                    echo '<input type="checkbox" id="'.$input_name.'" name="'.$input_name.'"'.($checked?' checked':'').' />';
                }
            ?>
            <input type="submit" />
        </form>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>        
        <script>
          function handleButtonClick(button){
            if ($(button).text().match("Check all")){
              $(":checkbox").prop("checked", true)
            } else {
              $(":checkbox").prop("checked", false)
            };
            updateButtonStatus();
          }
          function updateButtonStatus(){
            var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
            $("button").text(allChecked? "Uncheck all" : "Check all");
          }
          function updateCookie(){
            var elementValues = {};
            $(":checkbox").each(function(){
              elementValues[this.id] = this.checked;
            });
            elementValues["buttonText"] = $("button").text();
            $.cookie('elementValues', elementValues, { expires: 7, path: '/' })
          }
          $(":checkbox").on("change", function(){
            updateButtonStatus();
            updateCookie();
          });
          $("button").on("click", function() {
            handleButtonClick(this);
            updateCookie();
          });
          $.cookie.json = true;
        </script>
    </body>
</html>