动态下拉列表不工作

qnakjoqk  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(405)

我正在尝试使用ajax和php实现一个动态下拉列表。根据第一个选项列表中的索引值,第二个选项应该为我提供具有该id的名称列表。
选择1.php:

<html>
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
 $.ajax({
 type: 'post',
 url: 'fetch1.php',
 data: {
  get_option:val
 },
 success: function (response) {
  document.getElementById("new_select").innerHTML=response; 
 }
 });
}

</script>

</head>
<body>
<p id="heading">Dynamic Select Option Menu Using Ajax and PHP</p>
<center>
<div id="select_box">
 <select onchange="fetch_select(this.value);">
  <option>Select ID</option>
  <?php
  $host = 'localhost';
  $user = 'admin';
  $pass = 'admin';
  $dbname='kancha';
  $conn = new mysqli($host, $user, $pass, $dbname);
  // Check connection
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  } 

  $sql = "select distinct id from test";
  $select= $conn->query($sql);
  if ($select->num_rows > 0) {
    while($row = $select->fetch_assoc()) {
        echo "<option value='".$row['id']."'>".$row['id']."</option>";
       //echo "<option value=>".$row['id']."</option>";
    }
  } else {
    echo "0 results";
  }
  ?>
 </select>

 <select id="new_select">
 </select>

</div>     
</center>
</body>
</html>

获取1.php

<?php
if(isset($_POST['get_option']))
{
  $host = 'localhost';
  $user = 'admin';
  $pass = 'admin';
  $dbname='kancha';
  $conn = new mysqli($host, $user, $pass, $dbname);
  // Check connection
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  } 

  $id = $_POST['get_option'];
  //echo '$id';
 $sql = "select id, name from test where id='$id'";;
 $find= $conn->query($sql);

 if ($find->num_rows > 0) {
    while($row = $find->fetch_assoc()) {
        //echo "<option>".$row['name']."</option>";
        echo "<option value='".$row['id']."'>".$row['name']."</option>";
    }
  } else {
    echo "0 results";
  }
 exit;
}
?>

我的数据库如下所示:

SELECT * from test; 
id  name
1   Name1
2   Name2
1   Name3

第一个下拉列表工作正常。但是第二个下拉列表不起作用。我也附上了它的截图。跨文件发送数据有问题吗?不知道代码哪里出错了。
对于第二个选项列表,当我选择1时,我应该得到name1和name3作为选项,但是我没有得到任何选项。

编辑:select1.php中更正的javascript

hxzsmxv2

hxzsmxv21#

为selectbox中的选项添加值,现在没有从fetch\u select()传递值

zpjtge22

zpjtge222#

您正在为设置内容 new_select 使用错误的变量。
应该是的 response 而不是 val 更改为:

document.getElementById("new_select").innerHTML=response;

并为返回选项赋值。
比如:

echo "<option value='".$row['id']."'>".$row['name']."</option>";

并将您的sql字符串更改为以下内容,以使上述操作正常工作。

$sql = "select id, name from test where id='$id'";

确保你的 jquery.js 正在加载include。

相关问题