读取html选择标记内的php会话变量


Reading a php session variable inside an html select tag

我试图访问html选择标签内的php会话变量,因此我可以使用它来确定如何填充选项。

如果我在选择标签外回显变量,它会正常工作,但它不会在标签内回显。

我没有经验知道为什么。

下面是一段代码,我已经删除了不相关的代码,使其更容易阅读。

<?php
session_start();
$_SESSION['profile_type']='test';
?>
<!doctype html>
<html lang="en">
<head>
     <title>Profile</title>
</head> 
<?php
  echo $_SESSION["profile_type"];  //This WILL echo.
?>
<select id="profile" name="profile">
<?php
    echo $_SESSION["profile_type"];  //This will NOT echo.
?>
</select>    

正如Andrew已经说过的,<select> -标签内的内容必须是<option>类型的。因此,要列出要查找的会话变量,您需要像这样的内容

<select id="profile" name="profile">
    <option value="test">Text here</option>
    <?php
    echo "<option value=".$_SESSION['profile_type'].">".$_SESSION['profile_type']."</option>";
    ?>
</select> 

注意,$_SESSION$_GET$_POST等超全局变量不能在字符串中指定,必须像上面那样进行连接。

它可能会回显,但除非查看源代码,否则无法看到它。在<select>字段中,需要有<option value='foo'>Foo Text</option>行。Option标签填充了选择框。选择框是在提交时发送的选项值。