【问题标题】:How to repopulate checkboxes in form on refresh AND post the form values to page?如何在刷新时重新填充表单中的复选框并将表单值发布到页面?
【发布时间】:2015-03-29 01:30:33
【问题描述】:

当页面刷新或发送到另一个页面然后再返回时,我正在使用 ajax 脚本重新填充页面上的复选框。该脚本工作正常,因为在页面刷新后仍会检查复选框。

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

这里是 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['elementValues'] 访问PHP 中创建的cookie,即可在页面加载时重建过滤器
  • @darkbee 感谢您的回复。如果我能让它工作,这将是完美的。我回应了 $_COOKIE['elementValues'] 并显示:“2kandunder”:true,“2kto4k”:false,“4kandup”:false。所以我将这个添加到我的 php 中: if ($_COOKIE["2kandunder"]=true) { $arguments[] = "AND 2kandunder = 'yes'";我在正确的轨道上吗?这会将其放入字符串中,但无论它是“假”还是“真”,它总是在查询中。您能否向我展示一个快速示例,说明如何将其添加到我现有的 if(isset($_POST php?
  • 如果您的 javascript 放置在正文结束标记之后或 $(document).ready() 内,则可以正常工作。
  • @manta 很抱歉我的无知,但我不确定我是否遵循。你是说 $('#form').submit();如果放置正确应该可以工作吗?我在结束 body 标记之后有 ajax(至少我认为它的 ajax)脚本。我试图添加 $('#form').submit();在 repopulateFormELements() 之后;尝试让它提交我的表单,但它导致页面闪烁并转到“找不到页面”。我对 $(document).ready() 真的一无所知,并且在我拥有的现有 ajax 脚本中找不到它?

标签: javascript php ajax


【解决方案1】:

当您存储 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2020-07-28
    • 2023-03-25
    相关资源
    最近更新 更多