如何将JavaScript应用于PHP中的级联下拉(无AJAX)



我首先使用两个下拉列表,第二个列表为Sub类别。我想使用JavaScript的OnChange();获取子类别的值,但无法在代码中阐明如何使用它。PLZ指南。

  <th>Category</th>
  <td>
    <select name="category" class="frm" onChange="fun()">
    <?php
      include("data_connect.php");
      $data=mysqli_query($con,"select * from `category`");
      while($row=mysqli_fetch_array($data))
      {
          echo "<option value=".$row['c_id'].">".$row['name']."</option>";
      }
    ?>
    </select>
  </td>
</tr>
<tr>
  <th>Sub-Category</th>
  <td>
    <select name="sub_category" class="frm">
    <?php
    if(isset($_POST['sub']))
    {
        include("data_connect.php");
        $data=mysqli_query($con,"select * from `sub_category` where c_id=".$_POST['category']."");
        while($row1=mysqli_fetch_array($data))
        {
            echo "<option value=".$row1['s_id'].">".$row1['name']."</option>";
        }
    }
    ?>
    </select>
  </td>
</tr>

我将暂时忽略您的无效表结构,因为我不确定您要如何看待它。我现在只用形式包装您的内容,以便您至少有一些可以使用的东西。

此外,您的子类别查询也向SQL注入攻击开放。您应该使用绑定参数来解决此问题。您可以继续使用mysqli来做到这一点,但我个人建议切换到PDO。

<form method="post" id="categoryForm">
  <th>Category</th>
  <td>
    <select name="category" class="frm" onChange="document.getElementById('categoryForm').submit();">
    <?php
      include("data_connect.php");
      $data=mysqli_query($con,"select * from `category`");
      while($row=mysqli_fetch_array($data))
      {
          // check to see if we should re-select this value because it was submitted
          $isSelected = (!empty($_POST['category']) && $_POST['category'] == $row['c_id'] ? " selected" : "");
          echo "<option value='".$row['c_id']."'" . $isSelected . ">".$row['name']."</option>";
      }
    ?>
    </select>
  </td>
</tr>
<tr>
  <th>Sub-Category</th>
  <td>
    <select name="sub_category" class="frm">
    <?php
    // only if we've submitted the main category selection
    if(!empty($_POST['category']))
    {
        // no need to include data_connect.php again, it was already included above
        $data=mysqli_query($con,"select * from `sub_category` where c_id='".$_POST['category']."'");
        while($row1=mysqli_fetch_array($data))
        {
            echo "<option value=".$row1['s_id'].">".$row1['name']."</option>";
        }
    }
    ?>
    </select>
  </td>
</tr>
</form>

最新更新