使用php会话变量刷新后保留下拉选择值

时间:2018-05-24 14:22:44

标签: php html

Iam尝试下拉选择“粘性”,基本上我需要在会话变量中保留下拉选择的值,然后在doprdown选择中使用会话变量,这样当页面刷新时,值保留在下拉列表中。我想在php中这样做。

以下是选择的代码:

<?php
    $countryId = isset($_POST['country']) ? $_POST['country'] : '';
    asort($dirs);
    reset($dirs);
    echo '<option value="" disabled selected>Select Your Country</option>';
    foreach ($dirs as $p => $w):
        $selected = $countryId === $w ? 'selected' : '';
        echo '<option value="' . $w . '" ' . $selected . '>' . $w . '</option>';
    endforeach;
?>

非常感谢任何建议

1 个答案:

答案 0 :(得分:1)

制作名为savesession.php

的第二个文件
<?php
   if (isset($_GET['country_option'])) $_SESSION['country_option'] = $_GET['country_option'];

然后将您的代码更改为

<?php

   $countryId = isset($_POST['country']) ? $_POST['country'] : isset($_SESSION['country_option']) ? $_SESSION['country_option'] : '';
   asort($dirs);
   reset($dirs); 
   echo '<option value="" disabled selected>Select Your Country</option>';
   foreach($dirs as $p => $w):
       $selected = $countryId===$w ? 'selected' : '';
       echo '<option value="'.$w.'" '.$selected.'>'.$w.'</option>';
   endforeach;
?>
<script>
   function onDropDownChange(){

         var dd = document.getElementById("dropdownID");
         var selectedItem = dd.options[dd.selectedIndex].value;

         var ajax = new XMLHttpRequest();
         ajax.open("GET", "yourpage.com/savesession.php?country_option=" + selectedItem, true);

        ajax.send();
        ajax.onreadystatechange = function() {
              if (ajax.readyState == 4 && ajax.status == 200) {    
                  var data = ajax.responseText;    
              } 
        }
   }
</script>

然后向onchange="onDropDownChange"添加id="dropdownID"<select>,以便调用onDropDownChange上的javascript函数